How can I execute common code for each request?

Is it possible to find a function like Page_Load ? I have an MVC application and I need to run some code that loads or reloads with each page, or I call some controller. One common function for all classes?

I am trying to use Application_Start, but this is only done to launch the application for the first time. I am looking for some, like BeginRequest , but this function has been called several times, I only need it first when I load the page, and I need a final function, such as a constructor and destructor for the whole project.

Here is a sample code.

 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); } } 

document.ready not my case. And the call function of each controller is the last option. The code must be executed before calling any other function. And before it all ends, I need to run the end function. For example, first I need a built-in mysql connector for all classes. And in the end I need to close the mysql connection.

+3
source share
1 answer

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 { // ... } 
+6
source

Source: https://habr.com/ru/post/1485316/


All Articles