views:

246

answers:

2

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?

+2  A: 

Try overriding OnActionExecuted in the base controller or implementing the functionality as a filter.

krohrbaugh
+1 for the filter suggestion. I completely forgot about that.
Chris
+1  A: 

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?

Wyatt Barnett