ASP.NET MVC 5中的自定义错误页面

dem*_*emo 3 c# asp.net error-handling asp.net-mvc razor

我想在我的项目中添加自定义错误页面.我发现这个帖子关于我的问题,我尝试实现它.

所以:

  • 我加404.cshtml,404.html,500.cshtml500.html
  • 在添加的cshtml文件中设置响应状态代码
  • 评论添加HandleErrorAttribute到全局过滤器
  • 更新我的web.config文件

但现在当我尝试通过http://localhost:120/foo/bar我的应用程序所在的路径时,我http://localhost:120得到下一页:

'/'应用程序中的服务器错误.

运行时错误

描述:处理您的请求时发生异常.此外,执行第一个异常的自定义错误页面时发生另一个异常.请求已终止.

我开始<customErrors mode="Off"看看有什么问题.这是 - The resource cannot be found.这是合乎逻辑的.但是当我设置<customErrors mode="On"- 我再次得到运行时错误.

是什么导致它以及如何解决?


我的配置文件:

<system.web>
    <customErrors mode="Off" redirectMode="ResponseRewrite" defaultRedirect="~/500.cshtml">
        <error statusCode="404" redirect="~/404.cshtml"/>
        <error statusCode="500" redirect="~/500.cshtml"/>
    </customErrors>
</system.web>

<system.webServer>
    <httpErrors errorMode="Custom">
        <remove statusCode="404"/>
        <error statusCode="404" path="404.html" responseMode="File"/>
        <remove statusCode="500"/>
        <error statusCode="500" path="500.html" responseMode="File"/>
    </httpErrors>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

IIS 8.5版

scg*_*ugh 12

您使用的是哪个版本的IIS?如果7+然后使用<customErrors mode="Off">和忽略自定义错误<httpErrors>.使用下面的方法,后者将显示您的错误页面而不更改URL,IMO是处理这些事情的首选方式.

设置一个错误控制器并将你的404和500放在那里:

<httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="404" />
    <remove statusCode="500" />
    <error statusCode="404" path="/error/notfound" responseMode="ExecuteURL" />
    <error statusCode="500" path="/error/servererror" responseMode="ExecuteURL" />
 </httpErrors>
Run Code Online (Sandbox Code Playgroud)

在控制器中:

public class ErrorController : Controller
{
    public ActionResult servererror()
    {
        Response.TrySkipIisCustomErrors = true;
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return View();
    }

    public ActionResult notfound()
    {
        Response.TrySkipIisCustomErrors = true;
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        return View();
    }

}
Run Code Online (Sandbox Code Playgroud)

然后显然为每个覆盖的错误设置相应的视图.