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?
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.
Here is sample code.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
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.
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
{
// ...
}
An update to Jan's answer. The onExecutingAction
abstract method is public now not protected.
public virtual void OnActionExecuting(ActionExecutingContext context);
So, you can't use the protected
access modifier when you override. Make it public instead.
public class BaseController : Controller
{
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With