2016-04-02 19 views
0

ASP.NET MVC, böyle anahtarları bazı anahtar, çerez olarak değeriniuyuyamıyrom çerez Değerleri (NameValueCollection) - Ben çerez eklemek için Okulöncesi öğretmenlerinin kod kullanılan

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); 
    } 

ekleyip doldurun:

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

Okuma çerezi istediğimde Değerler boş. Ben Cookie Değerini

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; 
    } 

cevap

1

kontrol etmek Okulöncesi öğretmenlerinin kod kullanılır Sen çerez okurken Request.Cookies değil Response.Cookies kullanmak gerekir. Bunun yerine

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

ait

kullanın bir web uygulamasında

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

isteği tarayıcıdan gelir ve yanıt sunucu geri gönderdiği budur. Tarayıcıdan çerez verileri okurken Request.Cookies'i kullanmalısınız. Tarayıcıya gönderilecek çerezleri oluştururken bunları Response.Cookies'e eklemeniz gerekir.

1

Bunu kullanın.

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