C#/ASP.NET: can't remove cookies with Domain property specified

Viewed 11230

I have the following code in my login method:

Response.Cookies["cookie"].Value = "...";
Response.Cookies["cookie"].Domain = "domain.com";

This way the cookie is put into the main domain and all subdomains

However when I try to remove the cookies:

Response.Cookies["cookie"].Expires = DateTime.Now.AddYears(-1);

It doesn't work!

When I remove the 2 line of code where Domain property is specified, it works fine.

How can I solve this problem?

Thanks

5 Answers

Need to set domain and value with empty string. It does not work without value.

        var cookie = new HttpCookie(cookieName, string.Empty)
        {
            Expires = DateTime.Now.AddYears(-1),
            Domain = {YourDomain}
        };

        Response.Cookies.Add(cookie);

Tested in .Net 5

        foreach (var cookie in HttpContext.Request.Cookies)
        {
            Response.Cookies.Delete(cookie.Key, new CookieOptions()
            {
                Domain = Request.Host.Host // ADD
            });
        }

response header example

set-cookie: _example=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=YOUR.DOMAIN; path=/

CookieOptions() are optional and could be omitted, but then cookies in response will not have the domain name set.

Related