0

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?

2
  • 1
    Unless this application is only ever used by the same one person, I doubt you want to store a users cookie value in a global variable. Why not just use session state? Commented Sep 21, 2011 at 7:13
  • @UpTheCreek I agree with you. The global variable I meant here is not global to all users but it can be accessible anywhere in the MVC app for the particular user.. I can use session but if the data is lost from cookie still the data will float in session Commented Sep 21, 2011 at 7:44

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

or register it as a global filter
0

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

1 Comment

Can you tell me how I can use Attributes? I like the second option.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.