Remove Cookie from Web API 2 Response
asp.net-web-api, asp.net-web-api2, c#
Solution
Global.asax can remove cookies in the Application_EndRequest event. And you can set a variable to be later picked up by Application_EndRequest.
Step 1. Create an action filter which sets a variable in Context.Items:
public class NoResponseCookieAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
System.Web.HttpContext.Current.Items.Add("remove-auth-cookie", "true");
}
}
Step 2. Handle the Application_EndRequest event in your global.asax file. If the variable from Step 1 is present, remove the cookie.
protected void Application_EndRequest()
{
if (HttpContext.Current.Items["remove-auth-cookie"] != null)
{
Context.Response.Cookies.Remove(System.Web.Security.FormsAuthentication.FormsCookieName);
}
}
Step 3. Decorate your web api actions with the custom filter:
[NoResponseCookie]
public IHttpActionResult GetTypes()
{
// your code here
}
Problem
I am trying to do an authenticated web api request that does not reset the authentication cookie timeout. In the MVC world I would accomplish this by removing the FormsAuthenication cookie from the responce: ``` Response.Cookies.Remove(System.Web.Security.FormsAuthentication.FormsCookieName); ``` In Web API 2 I wrote a custom IHttpActionResult, and I am removing the Set-Cookie header from the response. This is however, not removing the header, as I still see the Set-Cookie header when the auth cookie is being updated for the requests that use this action result. Here is the custom IHttpActionResult: ``` public class NonAuthResetResult<T> : IHttpActionResult where T: class { private HttpRequestMessage _request; private T _body; public NonAuthResetResult(HttpRequestMessage request, T body) { _request = request; _body = body; } public string Message { get; private set; } public HttpRequestMessage Request { get; private set; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var msg = _request.CreateResponse(_body); msg.Headers.Remove("Set-Cookie"); return Task.FromResult(msg); } } ``` How do I edit the response header in Web API 2, because this is not working.