简体   繁体   English

无法获取Cookie值(NameValueCollection)-ASP.NET MVC

[英]cant get cookie Values (NameValueCollection) - ASP.NET MVC

I used belowe code to add cookie , I add some key, value in cookie , 我用下面的代码添加cookie,在cookie中添加了一些键,值,

 public static void AddCookie(this HttpContextBase httpContextBase, string cookieName, NameValueCollection cookieValues, DateTime expires, bool httpOnly = false)
    {
        var cookie = new HttpCookie(cookieName)
        {
            Expires = expires,
            //Value = httpContextBase.Server.UrlEncode(value),// For Cookies and Unicode characters
            HttpOnly = httpOnly
        };

        cookie.Values.Add(cookieValues);
        //httpContextBase.Response.Cookies.Add(cookie);
        System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
    }

and fill keys like this : 并填写这样的键:

NameValueCollection CookieValues = new NameValueCollection();
                CookieValues.Add("pid", shoppingCartViewModel.ProductId.ToString());
                CookieValues.Add("qty", "1");
                HttpContext.AddCookie(shoppingCartCookiName, CookieValues, DateTime.Now.AddDays(1));

when I want read cookie , Values are null . 当我想读取cookie时,值是null。 I used belowe code to check Cookie Value 我用下面的代码检查Cookie值

 public static NameValueCollection GetCookieValues(this HttpContextBase httpContext, string cookieName)
    {
        var cookie = System.Web.HttpContext.Current.Response.Cookies[cookieName];
        if (cookie == null)
            return null; //cookie doesn't exist

        // For Cookies and Unicode characters
        return cookie.Values;
    }

You need to use Request.Cookies not Response.Cookies while reading the cookie. 读取Cookie时,您需要使用Request.Cookies而不是Response.Cookies

Instead of 代替

System.Web.HttpContext.Current.Response.Cookies[cookieName]

Use 采用

System.Web.HttpContext.Current.Request.Cookies[cookieName]

In a web application the request is what comes from the browser and the response is what the server sends back. 在Web应用程序中,请求是来自浏览器的请求,响应是服务器发回的请求。 While reading cookie data from the browser you should use the Request.Cookies. 从浏览器读取cookie数据时,应使用Request.Cookies。 When you are constructing cookies to be sent to the browser you need to add them to Response.Cookies. 在构造要发送到浏览器的cookie时,需要将它们添加到Response.Cookies。

用这个。

HttpCookie cookie = HttpContext.Request.Cookies.Get("name");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM