且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使自定义错误页的ASP.NET MVC 4工作

更新时间:2023-02-25 22:28:41

我的当前设置(在MVC3,但我认为它仍然适用)就依赖于具有 ErrorController ,所以我用:

My current setup (on MVC3, but I think it still applies) relies on having an ErrorController, so I use:

<system.web>
    <customErrors mode="On" defaultRedirect="~/Error">
      <error redirect="~/Error/NotFound" statusCode="404" />
    </customErrors>
</system.web>

和控制器包含以下内容:

And the controller contains the following:

public class ErrorController : Controller
{
    public ViewResult Index()
    {
        return View("Error");
    }
    public ViewResult NotFound()
    {
        Response.StatusCode = 404;  //you may want to set this to 200
        return View("NotFound");
    }
}

和意见只是你实现它们的方式。我倾向于添加一点逻辑虽然,以显示堆栈跟踪如果应用程序是在调试模式下的错误信息。所以Error.cshtml看起来是这样的:

And the views just the way you implement them. I tend to add a bit of logic though, to show the stack trace and error information if the application is in debug mode. So Error.cshtml looks something like this:

@model System.Web.Mvc.HandleErrorInfo
@{
    Layout = "_Layout.cshtml";
    ViewBag.Title = "Error";
}
<div class="list-header clearfix">
    <span>Error</span>
</div>
<div class="list-sfs-holder">
    <div class="alert alert-error">
        An unexpected error has occurred. Please contact the system administrator.
    </div>
    @if (Model != null && HttpContext.Current.IsDebuggingEnabled)
    {
        <div>
            <p>
                <b>Exception:</b> @Model.Exception.Message<br />
                <b>Controller:</b> @Model.ControllerName<br />
                <b>Action:</b> @Model.ActionName
            </p>
            <div style="overflow:scroll">
                <pre>
@Model.Exception.StackTrace
                </pre>
            </div>
        </div>
    }
</div>