Is it safe to use such code?
Response.Cookies[cookieName].Path = Request.ApplicationPath + "/";
I want to know about all corner cases, please...
Is it safe to use such code?
Response.Cookies[cookieName].Path = Request.ApplicationPath + "/";
I want to know about all corner cases, please...
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;
}
}
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.
When generating a cookie, if the path you set differs in case from what the user typed, browsers won't store it.
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?
No, it's not safe, for the reasons that Will specified.
But... You may want to employ this technique to fulfill your intent.