When my application encounters an exception of type UnauthorizedAccessException during an AJAX request, I want to handle the behaviour myself and return a custom JSON response.
So I have overridden the OnException method in a base controller, which all my conrtollers inherit from, like this:
protected override void OnException(ExceptionContext filterContext)
{
var exception = filterContext.Exception;
if (exception is UnauthorizedAccessException)
{
filterContext.ExceptionHandled = true;
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
filterContext.HttpContext.Response.ContentType = "application/json";
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new { IsUnauthenticated = true });
filterContext.HttpContext.Response.Write(json);
filterContext.HttpContext.Response.End();
}
else
{
filterContext.Result = RedirectToAction("LogOut", "Account");
}
}
else
{
// Allow the exception to be processed as normal.
base.OnException(filterContext);
}
}
Now this pretty much does exactly what I want. If the exception occurs during an AJAX request, my JavaScript will get the correct JSON object back as desired.
However, the problem is that the application then suffers a HttpException internally, with message:
Cannot redirect after HTTP headers have been sent.
And the stack trace from the exception:
at System.Web.HttpResponse.Redirect(String url, Boolean endResponse, Boolean permanent) at System.Web.Security.FormsAuthenticationModule.OnLeave(Object source, EventArgs eventArgs) at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I get this exception information when adding a breakpoint to the Application_Error method of MvcApplication like this:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
LogError(ex);
}
So although my application is producing the result exactly as I want in terms of user experience. I have this "behind the scenes" exception that I really don't want to happen.
What is going wrong here? And what can I do to prevent the exception from occurring?
Application_Erroris an issue? If you comment it, does an error disapear?Application_Erroris fine.HttpExceptionwhen your controller throwsUnauthorizedAccessExceptionANDfilterContext.HttpContext.Request.IsAjaxRequest()isfalse?