MVC5自定义错误页面

时间:2014-09-05 12:17:29

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

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

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

提前致谢

3 个答案:

答案 0 :(得分:1)

请查看Ben Foster的这一页,详细解释您将遇到的问题以及可靠的解决方案。 http://benfoster.io/blog/aspnet-mvc-custom-error-pages

答案 1 :(得分:0)

在web.config中添加以下<customErrors>标记,如果系统无法找到请求的网址,则可以帮助您重定向到NotFound Error控制器的ServerError操作方法(状态代码404) )如果系统触发内部服务器错误(状态代码500),则重定向到错误控制器的<!--<Redirect to error page>--> <customErrors mode="On" defaultRedirect="~/Error/ServerError"> <error redirect="~/Error/NotFound" statusCode="404" /> </customErrors> <!--</Redirect to error page>--> 操作方法

Error

您必须创建一个ServerError控制器,其中包含NotFoundpublic class ErrorController : Controller { public ActionResult NotFound() { return View(); } public ActionResult Error() { return View(); } } 操作方法,该方法呈现相关视图以向用户显示正确的消息。

{{1}}

答案 2 :(得分:0)

如果您愿意,可以在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);
}