I am implementing <customErrors />
on my Asp.net MVC
application, so far so good.
I can test it by throwing HttpException
exceptions in the MVC, and the correct aspx
page gets returned.
However, i have a BusinessException
class, with a HttpStatusCode
property, which can be thrown from the application.
I need to capture this type of exception, and overwrite the Response Status Code to that specific HttpStatusCode
property, so the correct aspx
page will be returned.
Right now, even if i overwrite the Response.StatusCode property, i always get the 500.aspx
page.
Is there any solution to set the status code before "customErrors" kicks in?
public ActionResult ThrowBusinessException()
{
// this throws a Business Exception with NotFound status code. Should return 404.aspx, but it returns 500.aspx
throw new BusinessException("Product with ID = {0} was not found", HttpStatusCode.NotFound);
}
public class ErrorHandlerActionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
Exception ex = filterContext.Exception;
if(ex.GetType() == typeof(BusinessException))
{
BusinessException businessException = (BusinessException)ex;
filterContext.HttpContext.Response.StatusCode = (int)businessException.HttpStatusCode;
}
}
}
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/errors/500.aspx">
<error statusCode="404" redirect="~/errors/404.aspx" />
<error statusCode="403" redirect="~/errors/403.aspx" />
<error statusCode="500" redirect="~/errors/500.aspx" />
</customErrors>