Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute common code for every request?

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.

like image 269
user1173536 Avatar asked Oct 09 '13 08:10

user1173536


2 Answers

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
{
    // ...
}
like image 78
Jan Van Herck Avatar answered Oct 19 '22 09:10

Jan Van Herck


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);
    }
}
like image 5
Qudus Avatar answered Oct 19 '22 09:10

Qudus