开发者

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?


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜