Execute code on every request in ASP.NET MVC

回眸只為那壹抹淺笑 提交于 2019-12-08 10:56:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!