When to use Request.Cookies over Response.Cookies?

后端 未结 6 587
囚心锁ツ
囚心锁ツ 2020-12-02 07:30

Do I use response when at a page event (e.g. load) as this is a response from ASP.NET, and request when pressing a button as this is a response going to ASP.NET for processi

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 08:09

    When writing a cookie, use Response but reading may depend on your situation. Normally, you read from Request but if your application is attempting to get a cookie that has just been written or updated and the round trip to the browser has not occured, you may need to read it form Response.

    I have been using this pattern for a while and it works well for me.

    public void WriteCookie(string name, string value)
    {
        var cookie = new HttpCookie(name, value);
        HttpContext.Current.Response.Cookies.Set(cookie);
    }
    
    
    public string ReadCookie(string name)
    {
        if (HttpContext.Current.Response.Cookies.AllKeys.Contains(name))
        {
            var cookie = HttpContext.Current.Response.Cookies[name];
            return cookie.Value;
        }
    
        if (HttpContext.Current.Request.Cookies.AllKeys.Contains(name))
        {
            var cookie = HttpContext.Current.Request.Cookies[name];
            return cookie.Value;
        }
    
        return null;
    }
    

提交回复
热议问题