Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process cookies before any controller action is invoked in ASP.NET MVC

Where can I put some code that will be executed before any controller action is executed ?

I'm trying to replace default ASP.NET Session and I need to do this before any controller actions take place: get the cookies collection and check if I have new visitor with no cookies - than I'd add new "session ID" cookie that will than be available to the controllers. Otherwise (if there already is some "session ID" cookie) I will not do anything.

Where can I place the code that will do this ?

like image 394
Rasto Avatar asked Mar 11 '11 16:03

Rasto


2 Answers

I do it in Global.asax.cs

protected void Application_BeginRequest(object sender, EventArgs e)
{
            var c = Request.Cookies["lang"];
...
}
like image 182
Omu Avatar answered Oct 05 '22 22:10

Omu


There are a number of places you could do this, I'd say that the best place would be in an ActionFilter, overriding the OnActionExecuting event. If you want it to happen first, then you'll want to add the Order setting when you apply it.

If you want all your controllers to have it, then you could apply that filter to a base class, or just override the base class's OnActionExecuting method.

As a side note, for maximum testability you probably should have your not directly access the cookies collection in the request; that information (if needed) should come into the action method as a parameter or as a property on the controller that you can set in tests.

If you need to wire into the lifecycle earlier than OnActionExecuting (for any reason) you could also create a custom ControllerFactory, but I think that's probably overkill bsed on your description.

like image 30
Paul Avatar answered Oct 06 '22 00:10

Paul