0

Assume there are 2 cookie entries on the client side:

cookieExample1 = 1
cookieExaMPLE1 = 2

On the back end I'm using the following code:

var value1 = HttpContext.Current.Request.Cookies["cookieExample1"].Value;
logger.Info(value1); //result: 1
var value2 = HttpContext.Current.Request.Cookies["cookieExaMPLE1"].Value;
logger.Info(value2); //result: 1

My question is: how to make cookie values extraction case sensitive? I have modified the case of a cookie setting name in an existing application, but I'm still getting the old value that was associated with the previous name.

Yuriy Gavrishov
  • 773
  • 5
  • 22

2 Answers2

1

By using HttpContext.Current.Request.Cookies["cookieExaMPLE1"].Value you will always get the value of the first cookie with this case insensitive name. Cookies itself are not case-insensitive.

You can still access the cookies by a bit of a workaround:

for (int index = 0; index < cookies.Count; index++)
{
    writer.Write("<li>{0:D}> <b>", index);
    HttpUtility.HtmlEncode(cookies.GetKey(index), writer);
    writer.Write("</b> = &quot;");
    HttpUtility.HtmlEncode(cookies[index].Value, writer);
    writer.Write("&quot;</li>");
}
// -> cookieExample1=1 cookieExaMPLE1=2

To why cookies, or in general session parameters, are case insensitive, see .NET HttpSessionState Case Insensitivity . The short conclusion is to keep asp.net backwards compatible with older versions.

1

The indexer method is case-insensitive, but you can still iterate through the cookies and check the names yourself, e.g. with LINQ:

var request = HttpContext.Current.Request;
var cookie = request.Cookies.Cast<HttpCookie>().SingleOrDefault(cookie => cookie.Name == "case sensitive name");
John Wu
  • 44,075
  • 6
  • 37
  • 69