所有错误都在MVC ASP NET中自定义错误页面

时间:2017-05-15 07:09:35

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

我希望在我的应用中有401,404等错误代码的自定义错误页面。

我试过这个但不起作用? 在Web.config中

<customErrors mode="Off" /> //Under system.web

<httpErrors errorMode="Custom" existingResponse="Replace" >//Under system.webServer
  <clear />
  <remove statusCode="401"/>
  <error statusCode="401" responseMode="ExecuteURL" path="/Error/Unauthorized" />
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
  <error statusCode="500" responseMode="ExecuteURL" path="/Error" />
</httpErrors>

我还创建了错误控制器和未经授权的视图。

这怎么办?

1 个答案:

答案 0 :(得分:1)

示例:

<强>的web.config:

system.web添加

<customErrors mode="RemoteOnly"  defaultRedirect="~/error">//RemoteOnly means that on local network you will see real errors
  <error statusCode="401" path="~/Error/Unauthorized" />
  <error statusCode="404" path="~/Error/NotFound" />
  <error statusCode="500" path="~/Error" />
</customErrors>

system.webServer添加

<httpErrors errorMode="Detailed" /> 

<强>控制器: 您的控制器类似

public class ErrorController : Controller
{
    public ViewResult Index()
    {
        return View("Error");
    }
    public ViewResult NotFound()
    {
        Response.StatusCode = 404;
        return View("NotFound");
    }
}

查看:  和你的观点

@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>
    }
</div>

希望对你有帮助。