VJAI
VJAI

Reputation: 32758

Retrieving the data in every request in ASP.NET MVC

I need to retrieve the data from cookie in every request in ASP.NET MVC and store it in a global variable so that it'll be available throughout the application.

I've two questions here is there any event-handler in ASP.NET MVC where I can get the data from cookie in every request and what kind of global variable I can use to store this cookie value so it is available in all places?

Upvotes: 0

Views: 1466

Answers (3)

Simon Halsey
Simon Halsey

Reputation: 5480

You could go old school and handle the onrequest event in the asax file. That way you could abstract the code out to an httpmodule if you need to reuse the approach in another app. The filters approach is probably better though.

Upvotes: 0

Massimo Zerbini
Massimo Zerbini

Reputation: 3191

You can use a filter to get the cookie in every request. Create for example a class MyFilter

public class MyFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpCookie cookie = filterContext.HttpContext.Request.Cookies["myCookie"];

        //do something with cookie.Value
        if (cookie!=null) filterContext.HttpContext.Session["myCookieValue"] = cookie.Value;
        // or put it in a static class dictionary ...
        base.OnActionExecuting(filterContext);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
    }
}

Mark every controller class with [MyFilter] attribute. This example takes the cookie and puts the value in the session so it's available in all the views and all the controllers. Else you can put the cookie value in a static class that contains a static Dictionary and use the session ID as key. There are many way to store the cookie value and access it in every part of the application.

Upvotes: 3

Roberto Conte Rosito
Roberto Conte Rosito

Reputation: 2098

You can use Attributes on each request or make a custom Controller and handle "OnActionExecuting" (override)

Upvotes: 0

Related Questions