在Global.asax.cs中添加以下代码:
// 404错误页面的路由 routes.MapRoute( "Error", "Error/{type}", new { controller = "Error", action = "Index", type = UrlParameter.Optional } );
然后,创建一个名为ErrorController的控制器并添加以下代码:
public class ErrorController : Controller { // 未找到的视图或控制器的错误页面 public ActionResult Index(string type) { if (type == "404") { Response.StatusCode = 404; } else { Response.StatusCode = 500; }
return View();
}
}
最后,在Global.asax.cs中添加以下代码:
// 找不到控制器/视图时重定向到错误页面 protected void Application_Error() { Exception exception = Server.GetLastError(); Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null && httpException.GetHttpCode() == 404)
{
Response.Redirect("~/Error/404", true);
}
else
{
Response.Redirect("~/Error", true);
}
}
现在,当请求的Controller或View未找到时,用户将被重定向到Error控制器的Index动作,并显示404错误页面。