开发者

why cookies are always null after postback

开发者 https://www.devze.com 2023-01-11 21:10 出处:网络
i am trying to maintain some data into cookies but after postback if i check the value of the cookies in pageload the value is always null

i am trying to maintain some data into cookies but after postback if i check the value of the cookies in pageload the value is always null

this is how i set and get the cookies

private static string GetCookie(string name)
{
    return HttpContext.Current.Response != null ? HttpContext.Current.Response.Cookies[name].Value : string.Empty;
}

private static void SetCookie(string name, string va开发者_Python百科lue)
{
    HttpContext.Current.Response.Cookies[name].Value = value;
    HttpContext.Current.Response.Cookies[name].Expires = DateTime.Now.AddDays(ExpireTimeInDays);
}


GetCookie() needs to use Request.Cookie not Response.Cookie


HttpResponse.Cookies

ASP.NET includes two intrinsic cookie collections. The collection accessed through the Cookies collection of HttpRequest contains cookies transmitted by the client to the server in the Cookie header. The collection accessed through the Cookies collection of HttpResponse contains new cookies created on the server and transmitted to the client in the Set-Cookie header.

After you add a cookie by using the HttpResponse..::.Cookies collection, the cookie is immediately available in the HttpRequest..::.Cookies collection, even if the response has not been sent to the client.

So change your get to use the Request

0

精彩评论

暂无评论...
验证码 换一张
取 消