CustomExceptionAttribute whith $ajax POST call
I have this problem.
I write a CustomExceptionAttribute that redirect on customerrorpage.
My code work ok if I use a submit button on the MVC page and my controller throw an exception, but if my controller does same exception on ajax POST call, my custom error page not show.
I see with Fiddler that my CustomExceptionAttribute return a view with custom error etc but browser non show this page.
My code is:
AJAX.CALL
$.ajax({
url: '../Home/prova',
type: 'POST',
contentType: 'application/json',
dataType: "json",
data: {
},
success: function (data) {
if (data.redirect) {
window.location.href = data.redirect;
}
}
,
error: function (xhr) {
if (xhr.getResponseHeader('Content-Type').indexOf('application/json') > -1) {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
}
}
});
CustomErrorAttribute code:
public class CustomExceptionAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
// filterContext.Controller.ViewBag.OnExceptionError = "Exception filter called";
filterContext.HttpContext.Response.Write("Exception filter called");
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Shared/Error.cshtml",
MasterName = "~/Views/Shared/_Layout.cshtml",
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
// Prepare the response code.
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
//filterContext.HttpContext.Response.StatusCode = statusCode;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
Controller that throw exception
[HttpPost]
[CustomExceptionAttribute]
public JsonResult prova()
{
int a = 1;
int b = 0;
int result = a / b;
return Json("", JsonRequestBehavior.AllowGet);
}