0
votes

In ASP.Net Core application, how can I set a cookie and throw an exception during the same request?

In a Web API call, whenever I set a cookie using Response.Cookies.Append() the cookie header is only sent to the browser when returning from the call without throwing any exception.

If I append the cookie and then throw an exception, the cookie header is lost.

What gives? Am I missing something fundamental here? This doesn't seem like expected behavior.

1

1 Answers

0
votes

Instead of not handling the exception (returning a 500), you could catch the exception and output a cookie with a controlled response. Something like:

[HttpGet]
public IActionResult Get()
{
    try
    {
        throw new Exception("some exception");
    }
    catch (Exception ex)
    {
        // issue cookie and return response
        Response.Cookies.Append("someCookie", "my value");
        return BadRequest();
    }
}