Retrieving the data in every request in ASP.NET MVC

牧云@^-^@ 提交于 2021-02-11 13:51:29

问题


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?


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/7495847/retrieving-the-data-in-every-request-in-asp-net-mvc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!