显示自定义错误页面并显示异常详细信息

Fra*_*rio 5 error-handling asp.net-mvc exception asp.net-mvc-4

我有一个自定义错误控制器,如下所示:

public class ErrorsController : BaseController
{
    public ActionResult RaiseError(string error = null)
    {
        string msg = error ?? "An error has been thrown (intentionally).";
        throw new Exception(msg);
    }

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

    public ActionResult Error500()
    {
        Response.TrySkipIisCustomErrors = true;

        var model = new Models.Errors.Error500()
        {
            ServerException = Server.GetLastError(),
            HTTPStatusCode = Response.StatusCode
        };

        return View(model);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的Errors500.cshtml看起来像这样:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Error500</title>
</head>
<body>
    <div>
        An internal error has occurred.
            @if (Model != null && Model.ServerException != null &&                 HttpContext.Current.IsDebuggingEnabled)
    {
        <div>
            <p>
                <b>Exception:</b> @Model.ServerException.Message<br />
            </p>
            <div style="overflow:scroll">
                <pre>
                    @Model.ServerException.StackTrace
                </pre>
            </div>
        </div>
    }
    </div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我的web.config有我的错误处理程序指定如下:

<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace" >
  <remove statusCode="404" subStatusCode="-1" />
  <error statusCode="404" subStatusCode="-1" responseMode="ExecuteURL" path="/Errors/Error404" />
  <remove statusCode="500" subStatusCode="-1" />
  <error statusCode="500" subStatusCode="-1" responseMode="ExecuteURL" path="/Errors/Error500" />
</httpErrors>
Run Code Online (Sandbox Code Playgroud)

问题是:每次我调用/ errors/raiseerror来测试我的500处理; 我被重定向到errors/error500(罚款).但是,异常数据不会在页面上呈现,因为Server.GetLastError()调用返回null而不是RaiseError()抛出的异常.

处理自定义500错误页面的最佳方法是什么,该自定义页面也可以呈现异常详细信息?

Len*_*rri 14

最简单的方法是:

使用MVC的内置支持来处理异常.默认情况下,MVC使用HandleErrorAttribute在以下位置注册App_Start\FilterConfig.cs:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}
Run Code Online (Sandbox Code Playgroud)

现在确保您有一个ErrorViews\Shared文件夹中调用的视图.默认情况下,视图具有类型的模型,HandleErrorInfo其属性名为Exception.如果您需要,可以显示"异常"消息和其他详细信息:

Error.cshtml

@model HandleErrorInfo

@if(Model != null)
{       
    @Model.Exception.Message
}
Run Code Online (Sandbox Code Playgroud)

您可以Error.cshtml按照自己想要的方式自定义页面...