<customerrors>更改状态代码

时间:2016-02-22 11:16:08

标签: asp.net asp.net-mvc custom-error-pages custom-errors

我正在我的<customErrors />应用程序上实现Asp.net MVC,到目前为止一直很好。

我可以通过在MVC中抛出HttpException个异常来测试它,并返回正确的aspx页面。

但是,我有一个BusinessException类,具有HttpStatusCode属性,可以从应用程序中抛出。

我需要捕获此类异常,并将响应状态代码覆盖到该特定HttpStatusCode属性,以便返回正确的aspx页面。

现在,即使我覆盖了Response.StatusCode属性,我也总是得到500.aspx页面。

是否有任何解决方案可以在&#34; customErrors&#34;之前设置状态代码。踢了?

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>

0 个答案:

没有答案