Reputation: 3262
I'm trying to remove specific Set-Cookie
header from HttpResponseHeaders
in OnActionExecuted
method of ActionFilter
.
I'm having few issues with that:
Set-Cookie
can have multiple
entries.Currently I'm removing all cookies, but this 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);
}
Upvotes: 8
Views: 10835
Reputation: 75306
From the link:
You cannot directly delete a cookie on a user's computer. However, you can direct the user's browser to delete the cookie by setting the cookie's expiration date to a past date. The next time a user makes a request to a page within the domain or path that set the cookie, the browser will determine that the cookie has expired and remove it.
So, how to remove/delete cookie in ASP.NET Web Api at action filter level, just try to set expiration date of cookie to a past 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);
}
Upvotes: 5