asp.net mvc4中自定义404页面

邱秋 • 2018年07月25日 • 阅读:1002 • asp.net

定义 404 方法当然有很多种。不同的方法所展现的形式也不一样,用户所体验也不一样。以下提供 2 两种

方法一

1.在 web.config 中找到节点<system.web>中启用 404 配置

<customErrors defaultRedirect="~/Error" mode="On" redirectMode="ResponseRedirect">
<error redirect="/Error" statusCode="404" />
</customErrors>

2.定义一个 controllers Error(这个随你) ,在 action 中如下定义

public ActionResult Index()
{
    Response.Status = "404 Not Found";
    Response.StatusCode = 404;
    return View();
}

这种方式 默认为给你的 url 加上 ?aspxerrorpath=/ 比如:http://localhost/Error??aspxerrorpath=/123456 故不推荐试用

方法二:

打开 Global.asax 文件 定义错误转向地址(controller/action)

protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
    {
        Response.Redirect("/Error");
    }
}

注意事项: 在开发时候,我们经常会在 Global.asax 中的 Application_Error 方法中使用 Response.Redirect 方法跳转到自定义错误页,但有时候(特别是当站点部署到 IIS 后)Application_Error 方法中使用 Response.Redirect 方法会失效,当发生异常错误后还是显示的默认错误黄页。

其根本原因是尽管我们在 Application_Error 方法中使用了 Response.Redirect 方法,但是当系统发生异常错误后 Asp.Net 认为异常并没有被处理,所以不会跳转到 Application_Error 方法中 Response.Redirect 指向的页面,最终还是会跳转到默认错误黄页。

解决这个问题的办法很简单就是在 Application_Error 方法中使用 Response.Redirect 做跳转前,先调用 Server.ClearError() 方法告诉系统发生的异常错误已经被处理了,这样再调用 Response.Redirect 方法系统就会跳转到自定义错误页面了。

我,秦始皇,打钱!