Search code examples
c#asp.netasp.net-mvchttpcontexthttpcookie

MVC - Delete cookie when response code is Bad Request won't work, but the same code on status code OK works


I have a MVC controller that has a login method. If the login parameters are false, an exception is raised and in that case I need to remove one cookie. The problem is that the code works if the Response.StatusCode = OK. But since an exception is thrown, I wanna set the StatusCode = 400. Can this be done? I have a feeling that only on StatusCode = OK(200) you can manipulate cookies. I have tried this also with StatusCode = 401 and it won't work

This is my code:

HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
HttpCookie cookie = HttpContext.Request.Cookies["login_cookie"];
if (cookie != null)
{
    cookie.Expires = DateTime.Now.AddYears(-1);
    HttpContext.Response.Cookies.Add(cookie);
    HttpContext.Request.Cookies.Remove("login_cookie");
}

Solution

  • The problem is that in the core of our application Set-Cookie in a Header was always cleared.