Execute code on every request in ASP.NET MVC
-
05-07-2019 - |
Question
I have a controller that all my controllers inherit from and I need to execute some code for every controller request. I tried the following:
protected override void Execute(System.Web.Routing.RequestContext requestContext)
{
if (Session["mallDetected"] == null)
{
Session["mallDetected"] = DateTime.Now.Ticks;
IList<Mall> malls = Mall.FindNearestByIp(Request.UserHostAddress);
if (malls.Count > 0)
{
Session["mall"] = malls[0];
}
}
base.Execute(requestContext);
}
But apparently session state isn't available in the Execute method until AFTER the call to base.Execute(), which doesn't work for me. Is there a place where I can execute this session code for each request in ASP.NET MVC?
Solution
Try overriding OnActionExecuted
in the base controller or implementing the functionality as a filter.
OTHER TIPS
If you want something to happen in an ASP.NET application on every request, you are probably better off building it into an IHttpModule rather than building it into a controller. How do you guarantee your successor will implement your controller correctly?