Is the name of a cookie case sensitive?

后端 未结 5 1945
面向向阳花
面向向阳花 2020-12-10 10:28

A HTTP Cookie consists of a name-value pair and can be set by the server using this response:

HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: name=value
         


        
5条回答
  •  青春惊慌失措
    2020-12-10 10:56

    At the bottom is a script that demonstrates Cookie case sensitivity on browsers and .Net framework. Every time it is run, it will insert a cookie named xxxxxxxxxx, with random upper/lower cases. Press F5 to refresh a few times to insert a few cookies.

    I have teste it on Chrome and Firefox, and both demonstrate similar behavior, something like below:

    Request.Cookies["xxxxxxxxxx"].Name returns: xxxxXxXXXX
    All XXXXXXXXXX Cookies:
    
        xxxxXxXXXX
        xXxxXxXXXx
        XxxxxXxXXx
        XXXxXxXXxX
    

    It shows:

    • Cookies are case sensitive on Chrome and Firefox
    • .Net Framework can handle case sensitive cookies (that's why it could loop through all those cookies)
    • Request.Cookies["xxxxxxxxxx"] is case insensitive (that's why it returns the first cookie that case-insensitively matches the name)

    As mentioned in other answers, the new RFC indicates that cookies are case sensitive, and both Chrome and Firefox seem to handle it that way. .Net Framework can handle case-sensitive cookies, but it really wants to treat cookies case-insensitively, and many of its functions do treat cookies that way (Cookies[], Cookies.Set() etc.). This inconsistency can cause many hard to track bugs.

    TestCookie.aspx:

    <%@ Page language="c#" AutoEventWireup="false" validateRequest=false %>
    
    
    
        Test Cookie Sensitivity
    
    
    

    Request.Cookies["xxxxxxxxxx"].Name returns: <% HttpCookie cookie2 = Request.Cookies["xxxxxxxxxx"]; if (cookie2 == null) Response.Write("No cookie found"); else Response.Write(cookie2.Name); %>

    All XXXXXXXXXX Cookies:

      <% foreach (string key in Request.Cookies.Keys) if (key.ToLower() == "xxxxxxxxxx") Response.Write("
    • " + key + "
    • "); Random rand = new Random(); StringBuilder name = new StringBuilder(); for (int i = 0; i < 10; i++) { if (rand.Next(2) == 0) name.Append('x'); else name.Append('X'); } HttpCookie cookie = new HttpCookie(name.ToString()); cookie.HttpOnly = true; cookie.Expires = DateTime.Now.AddMonths(1); Response.Cookies.Add(cookie); %>

提交回复
热议问题