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 ?
I do it in Global.asax.cs
protected void Application_BeginRequest(object sender, EventArgs e)
{
var c = Request.Cookies["lang"];
...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With