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

时间:2016-04-02 09:59:39

标签: c# asp.net-mvc cookies

我使用下面的代码添加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);
    }

并填写如下键:

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

当我想要读取cookie时,值为null。 我使用下面的代码来检查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;
    }

2 个答案:

答案 0 :(得分:1)

在阅读Cookie时,您需要使用Request.Cookies而不是Response.Cookies

而不是

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

使用

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

在Web应用程序中,请求来自浏览器,响应是服务器发回的内容。从浏览器读取cookie数据时,您应该使用Request.Cookies。当您构建要发送到浏览器的cookie时,您需要将它们添加到Response.Cookies。

答案 1 :(得分:1)

使用此功能。

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