ASP.NET MVC5自定义错误命中500而不是400,403或404

时间:2015-02-20 02:07:07

标签: c# web-config asp.net-mvc-5 elmah custom-errors

我为我的网站设置了自定义错误,因为我的Web.config显示如下:

<system.web>
    <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Error/Error400">
      <error statusCode="400" redirect="~/Error/Error404"/>
      <error statusCode="404" redirect="~/Error/Error404" />
      <error statusCode="403" redirect="~/Error/Error403" />
      <error statusCode="500" redirect="~/Error/Error500" />
    </customErrors>   
</system.web>

<system.webServer>  
    <httpErrors errorMode="Custom" existingResponse="Replace">
        <remove statusCode="400" />
        <error statusCode="400" path="/Error/Error400" responseMode="ExecuteURL" />
        <remove statusCode="403" />
        <error statusCode="403" path="/Error/Error403" responseMode="ExecuteURL" />
        <remove statusCode="404" />
        <error statusCode="404" path="/Error/Error404" responseMode="ExecuteURL" />      
        <remove statusCode="500" />
        <error statusCode="500" path="/Error/Error500" responseMode="ExecuteURL" />
    </httpErrors>
</system.webServer>

我从我的控制器中抛出这样的错误:

throw new HttpException((int)HttpStatusCode.BadRequest, "The checklist Id is not specified. EntityId: " + this.LoggedInEntity.EntityId + "; userId: " + this.LoggedInUser.UserId);

处理自定义错误页面请求的错误控制器是:

public class ErrorController : Controller
{
    public ActionResult Error400()
    {
        ErrorViewModel error = new ErrorViewModel();
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return View(error);
    }

    public ActionResult Error403()
    {
        ErrorViewModel error = new ErrorViewModel();
        Response.StatusCode = (int)HttpStatusCode.Forbidden;
        return View(error);
    }

    public ActionResult Error404()
    {
        ErrorViewModel error = new ErrorViewModel();
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        return View(error);
    }

    public ActionResult Error500()
    {
        ErrorViewModel error = new ErrorViewModel();
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return View(error);
    }
}

但是,在示例抛出异常(400错误)中,400动作不会被调用。而是调用500动作。如何让它为抛出的错误调用正确的400动作?

我正在使用ELMAH进行错误记录,并显示正确的错误代码: Elmah log

1 个答案:

答案 0 :(得分:1)

根据以下答案,ResponseRewrite不适用于MVC路由:

https://stackoverflow.com/a/3770265/758765

如果您阅读Bens(awesome)博客文章,他会使用实际文件来表示404和500响应,而不是MVC控制器。