Unable to Set Cookie in ASP.NET MVC IExceptionFilter

384 views Asked by At

I've implemented a custom IExceptionFilter to handle an exception some users are experiencing with a third party library our application is consuming. When this particular error state occurs, I need to modify the user's cookies (to clear their session state), but what I am finding is that no cookies seem to make it out of the filter. Not sure what's wrong or even how to debug it.

I've modified the functional bits filter to simplify the intent, but here's the gist of the filter. I've ensured that it is the first filter to run on the controller and tested removing the HandleErrorAttribute filter as well to no avail. After the below code runs, "somecookie" is never set on the client.

public class HandleSessionErrorAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null) throw new ArgumentNullException("filterContext");

        var exception = filterContext.Exception as HttpException;

        if (exception != null && exception.Message.Equals("The session state information is invalid and might be corrupted."))
        {
            filterContext.HttpContext.Response.Cookies.Add(new HttpCookie("somecookie")
            {
                Value = DateTime.Now.ToString(),
                Expires = DateTime.Now.AddMinutes(5),
            });              
        }
    }
}
1

There are 1 answers

0
Nathan Taylor On

Okay, figured it out. Two issues were preventing the logic from succeeding:

  • The HandleErrorAttribute must run before any attribute which modifies the response. Part of the implementation of HandleErrorAttribute is to Clear() the response.
  • CustomErrors must be On for this to work

The initialization code which worked:

GlobalFilters.Filters.Add(new HandleErrorAttribute() { Order = 0 });
GlobalFilters.Filters.Add(new HandleSessionErrorAttribute() { Order = 1 });