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

C# 无法获取cookie值(NameValueCollection)-ASP.NET MVC,c#,asp.net-mvc,cookies,C#,Asp.net Mvc,Cookies,我使用belowe代码添加cookie,我在cookie中添加了一些键和值 public static void AddCookie(this HttpContextBase httpContextBase, string cookieName, NameValueCollection cookieValues, DateTime expires, bool httpOnly = false) { var cookie = new HttpCookie(cookieNa

我使用belowe代码添加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。 我使用belowe代码检查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;
    }

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

而不是

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


在web应用程序中,请求是来自浏览器的,响应是服务器发回的。从浏览器读取cookie数据时,应使用Request.Cookies。构建要发送到浏览器的cookie时,需要将其添加到Response.cookies。

在读取cookie时,需要使用
Request.cookies
而不是
Response.cookies

而不是

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

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

使用此选项

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

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