【问题标题】:MVC5 custom error pageMVC5 自定义错误页面
【发布时间】:2014-09-05 12:17:28
【问题描述】:

当用户尝试调用不存在的控制器方法或在 MVC5 Web 应用程序访问期间发生授权错误时,我想显示自定义错误页面。

是否有任何网站解释了如何为 MVC5 网站设置自定义错误页面。

提前致谢

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-5


【解决方案1】:

查看 Ben Foster 的此页面,非常详细地解释了您将遇到的问题和可靠的解决方案。 http://benfoster.io/blog/aspnet-mvc-custom-error-pages

【讨论】:

  • 感谢您的链接。它有帮助
【解决方案2】:

在web.config中添加<customErrors>标签,如果系统找不到请求的url(状态码404),会重定向到Error控制器的NotFoundaction方法,重定向到@987654324 @ 系统触发内部服务器错误时错误控制器的操作方法(状态码 500)

<!--<Redirect to error page>-->
<customErrors mode="On" defaultRedirect="~/Error/ServerError">
  <error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>
<!--</Redirect to error page>-->

您必须创建一个 Error 控制器,其中包含 ServerErrorNotFound 操作方法,用于呈现相关视图以向用户显示正确的消息。

public class ErrorController : Controller
{
    public ActionResult NotFound()
    {
        return View();
    }
    public ActionResult Error()
    {
        return View();
    }
}

【讨论】:

  • 您不应该在错误页面上重定向。仅当您还拥有 redirectMode="ResponseRewrite" 时才允许使用 &lt;error redirect="" /&gt;
【解决方案3】:

如果您愿意,可以像这样处理 globalasax Application_Error() 方法中的错误:

protected void Application_Error(object sender, EventArgs e) {
    var exception = Server.GetLastError();
    Response.Clear();

    string redirectUrl = "/Error"; // default
    if (exception is HttpException) {
        if (((HttpException)exception).GetHttpCode() == 404) {
            redirectUrl += "/NotFound";
        } else if (((HttpException)exception).GetHttpCode() == 401) {
            redirectUrl += "/NotAuthorized";
        } else { 
            redirectUrl += "?e=" + ((HttpException)exception).GetHttpCode();
        }
        Server.ClearError();
        Response.Clear();
    }
    Response.Redirect(redirectUrl);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-26
    • 2013-08-26
    • 2014-02-28
    • 2016-04-25
    • 2013-02-27
    • 2013-09-16
    • 2011-03-26
    • 2013-11-12
    相关资源
    最近更新 更多