I have a custom filter that I've used for years for handling RequestValidationException
s in a more user-friendly way. It works without issues in all scenarios until I introduce an Area:
public class HandleHttpRequestValidationExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
//base.OnException(filterContext);
if (!(filterContext.Exception is HttpRequestValidationException))
return;
const string viewName = "~/Views/Errors/HttpRequestValidationException.cshtml";
var result = new ViewResult
{
ViewName = viewName,
ViewData = { Model = filterContext.Exception.Message }
};
//result.ViewBag.StatusCode = 200;
filterContext.Result = result;
filterContext.RouteData.Values["area"] = "";
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 200;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
filterContext.HttpContext.Server.ClearError();
}
}
...registered in FilterConfig:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//filters.Add(new HandleErrorAttribute());
filters.Add(new HandleMemberIsNotActivatedOrWaiveredAttribute());
filters.Add(new HandleMemberNotAuthorizedException());
filters.Add(new HandleHttpRequestValidationExceptionAttribute());
}
}
Any RequestValidationException
thrown gets handled without issues (I get my pretty error page with some user-friendly description of what happened and what to do about it) except if one is thrown in an Area. In that case, I get a blank response with customErrors="On" (and the detailed YSOD if customErrrors="Off"). If I remove my filter, then I get the no-details YSOD (which is also pointless). Either way, Application_Error in Global.asax.cs does not get fired. Moreover, all my other custom filters and global exception handling works without any issues regardless of where the exception is thrown from.
How can I handle RequestValidationException
in a user-friendly manner regardless of where the exception originates from (regardless of whether or not it is thrown from within an Area
)?
Update: even doing a filterContext.Result = new RedirectResult("/");
results in the same blank page (and stepping through it indicates all is well, but no proper response).
I believe you are going to need to forward the error model out of the area to your error controller in order to generate the view. or you will have to route your error controller to the area.
Look at this link. Redirect From Action Filter Attribute