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);
}
Add(new HttpCookie("ASP. NET_SessionId", "")); This code example clears the session state from the server and sets the session state cookie to null. The null value effectively clears the cookie from the browser.
To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.
set() The set() method of the cookies API sets a cookie containing the specified cookie data. This method is equivalent to issuing an HTTP Set-Cookie header during a request to a given URL.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With