0

I'm having rather weird issue. Hoping anyone can shed some light, since I couldn't find an answer anywhere.

Scenario: controller action is called and exception occurs. At the same time I add a new cookie to Response.Cookies.

But no cookie is sent with Response (checked in Fiddler even).

The interesting thing is that the same scenario worked for me before in web forms using generic handler.

Any thoughts?

Code snippet

[HttpGet]
public FileContentResult MyAction()
{
    HttpCookie newCookie = new HttpCookie("error-exc", "error") { HttpOnly = false };
    this.HttpContext.Response.Cookies.Add(newCookie);

    throw Exception("test");
}
Pavdro
  • 411
  • 1
  • 9
  • 18
  • Looks like the exception breaks the response pipeline. You can add a global error handling at controller level or Application_OnError event of global.asax. – Dilish Dec 13 '13 at 14:33

1 Answers1

2

One way to make sure your cookie is sent to the client is to override the OnException() virtual method in your controller:

protected override void OnException(ExceptionContext filterContext) {
    filterContext.ExceptionHandled = true;
    filterContext.HttpContext.Response.StatusCode = 500;
    filterContext.HttpContext.Response.StatusDescription = "Internal server error";
    // whatever...
    base.OnException(filterContext);    
}
Mauro Cerutti
  • 684
  • 4
  • 9
  • Out of curiosity.. When you do this, is the current state of your response, including cookies, kept? – Andre Pena Dec 13 '13 at 14:00
  • thanks! I was thinking the same, but was hoping maybe it's just a bug and I can just leave exception be. – Pavdro Dec 13 '13 at 14:56