问题
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?
回答1:
Try overriding OnActionExecuted in the base controller or implementing the functionality as a filter.
回答2:
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?
来源:https://stackoverflow.com/questions/1209154/execute-code-on-every-request-in-asp-net-mvc