我怎么能执行普通code为每个请求? [英] How can I execute common code for every request?
问题描述
是否有可能找到像的Page_Load
功能?我有MVC应用程序,我需要运行一些code每次加载页面时,或重新加载,否则我调用一些控制器。一切类的一个共享功能?
Is there any possibility to find function like Page_Load
? I have MVC application and I need run some code every page is loaded, or reloaded, or I call some controller. One shared function for everything classes?
我尝试的Application_Start,但只执行首次运行的应用程序。我搜索了一些像的BeginRequest
,不过这个功能已经调用好几次,我只需要第一次,当我加载页面,我需要结束的功能,如构造函数和析构函数为整个项目
I try Application_Start, but this execute only for first time application run. I search some like BeginRequest
, but this function have been call several times, I need only first, when I load page and I need end function, like constructor and destructor for whole project.
下面是示例code。
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
的document.ready
不是我的情况。并调用函数的每个控制器是最后的选择。任何其他函数被调用之前,必须执行code。而所有年底前,我需要运行结束的功能。例如,在首先我需要创造的MySQL Connector所有类共享。而在最后,我需要关闭MySQL连接。
document.ready
isn't my case. And call function every controller is last option. The code must be executed before any other function have been called. And before all end, i need run end function. For example, at first I need created mysql connector shared for all classes. And at end I need close mysql connection.
推荐答案
请所有的控制器从定制BaseController继承:
Make all your controllers inherit from a custom BaseController:
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
// your code here
}
}
public class HomeController : BaseController // instead of Controller
{
// ...
}
这篇关于我怎么能执行普通code为每个请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!