Is it possible to delete subdomain cookies?

2019-01-18 11:39发布

If there is a cookie set for a subdomain, metric.foo.com, is there a way for me to delete the metric.foo.com cookie on a request to www.foo.com? The browser (at least Firefox) seems to ignore a Set-Cookie with a domain of metric.foo.com.

2条回答
混吃等死
2楼-- · 2019-01-18 12:30

Cookies are only readable by the domain that created them, so if the cookie was created at metric.foo.com, it will have to be deleted under the same domain as it was created. This includes sub-domains.

If you are required to delete a cookie from metric.foo.com, but are currently running a page at www.foo.com, you will not be able to.

In order to do this, you need to load the page from metric.foo.com, or create the cookie under foo.com so it can be accessable under any subdomain. OR use this:

Response.cookies("mycookie").domain = ".foo.com"

...while creating it, AND before you delete it.

..untested - should work.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-18 12:31

I had the same problem with subdomains. For some reason getting the cookie first from the request didn't work. Instead I ended up just creating a new cookie with the same cookie name, and expiry date in the past. That worked perfectly:

void DeleteSubdomainCookie(HttpResponse response, string name)
{
    HttpCookie cookie = new HttpCookie(name);
    cookie.Expires = DateTime.Now.AddMonths(-1);
    cookie.Domain = ".yourdomain.com";
    response.Cookies.Add(cookie);
}
查看更多
登录 后发表回答