Question

Is it safe to use such code?

Response.Cookies[cookieName].Path = Request.ApplicationPath + "/";

I want to know about all corner cases, please...

Was it helpful?

Solution

In short, no, it's not safe. Using cookie paths is fraught with problems as they are case sensitive in IE and Chrome, but not FF. This means any mismatch in path case will stuff things up.

  1. When generating a cookie, if the path you set differs in case from what the user typed, browsers won't store it.

  2. When the user returns, if the path they enter differs in case from the first trip, the browser won't supply the cookie with the request.

What problem are you trying to solve?

OTHER TIPS

If your application runs in the root of a domain, Request.ApplicationPath == "/". Hence, with your code, the path of your cookie will be //. You can dodge around this problem by doing this:

cookie.Path = Request.ApplicationPath;
if (cookie.Path.Length > 1) cookie.Path += '/';

As Will correctly points out, you will want to make sure that your application enforces a consistent casing of URLs (i.e. redirect all requests with URLs containing uppercase letters to their lowercase equivalent).

Other than that, I believe you should be fine doing this. If you want all of your cookies to be "application scoped", consider creating a custom IHttpModule with code like this (or extend global.asax.cs):

private void Application_EndRequest(object sender, EventArgs e)
{
    var app = (HttpApplication)sender;

    var cookiePath = app.Request.ApplicationPath;
    if (cookiePath.Length > 1) cookiePath += '/';

    foreach (string name in app.Response.Cookies.AllKeys)
    {
        var cookie = app.Response.Cookies[name];
        cookie.Path = cookiePath;
    }
}

No, it's not safe, for the reasons that Will specified.

But... You may want to employ this technique to fulfill your intent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top