How to delete a specific cookie from HttpRequestHeaders in WebApi

I am trying to remove a specific Set-Cookie header from HttpResponseHeaders in the OnActionExecuted ActionFilter method.

I have few problems with this:

  • I do not see a way to list the headers. The collection is always empty, even if I see headers in the debugger.
  • Because I cannot list, I cannot delete a specific title. I can delete all headers with the same key, but Set-Cookie can have multiple entries.

I am currently deleting all cookies, but that is not what I want.

 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { HttpResponseHeaders headers = actionExecutedContext.Response.Headers; IEnumerable<string> values; if (headers.TryGetValues("Set-Cookie", out values)) { actionExecutedContext.Response.Headers.Remove("Set-Cookie"); } base.OnActionExecuted(actionExecutedContext); } 
+5
source share
1 answer

From link :

You cannot directly delete the cookie on the user's computer. However, you can direct the user's browser to delete cookies by setting the cookie expiration date to a past date. The next time the user makes a request for a page in the domain or path that sets the cookie, the browser determines that the cookie has expired and deleted it.

So, how to remove / delete cookies in ASP.NET Web Api at the action filter level, try setting the cookie expiration date to the last date:

 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { var response = actionExecutedContext.Response; var request = actionExecutedContext.Request; var currentCookie = request.Headers.GetCookies("yourCookieName").FirstOrDefault(); if (currentCookie != null) { var cookie = new CookieHeaderValue("yourCookieName", "") { Expires = DateTimeOffset.Now.AddDays(-1), Domain = currentCookie.Domain, Path = currentCookie.Path }; response.Headers.AddCookies(new[] { cookie }); } base.OnActionExecuted(actionExecutedContext); } 
+4
source

Source: https://habr.com/ru/post/1234026/


All Articles