asp.net mvc - 从应用程序加载任何页面时执行的通用代码

发布于 2024-12-21 00:24:04 字数 68 浏览 5 评论 0原文

这样的代码会去哪里? Asp.net mvc 3 应用程序内部是否有一个常用的执行块 - 每次加载任何页面时都会执行该块?

Where would such code go? Is there a commonly executed block inside Asp.net mvc 3 application - something that gets executed every time any page is loaded?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ㄟ。诗瑗 2024-12-28 00:24:04

您可以通过两种方式执行此操作:
首先,您可以从 System.Web.Mvc.Controller 继承基本控制器。然后,您可以为您的应用程序使用继承的基类。通过这种方式,您可以通过覆盖 OnActionExecuting 方法。

第二个也是更好的解决方案是使用自定义操作筛选器。创建一个自定义过滤器并在 Global.asax 文件中全局注册它,如下所示:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new YourCustomFilter());
}

You can do this by two ways:
First, you can inherit a base Controller from System.Web.Mvc.Controller. Then you use this base class inherits for your application. By this way, you can handle all action executions by overriding OnActionExecuting method of your base controller.

Second and better solution is using Custom Action Filters. Create a custom filter and register it globally in Global.asax file like this:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new YourCustomFilter());
}
还不是爱你 2024-12-28 00:24:04

Global.asax(例如:http://www.dotnetcurry。 com/ShowArticle.aspx?ID=126)或 _Layout 内,这取决于您在做什么。

您知道 Global.asax 文件也可以在 ASP.NET Webforms 中使用。

Global.asax (ex: http://www.dotnetcurry.com/ShowArticle.aspx?ID=126) or inside the _Layout, it depends on what you're doing.

Just so you know the Global.asax file is also available in ASP.NET Webforms.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文