1、Global.asax.cs中,加入如下代码
protected void Application_Error(Object sender, EventArgs e) { Exception exception = Server.GetLastError(); if (exception != null) { HttpException httpException = exception as HttpException; if (httpException != null) { int errorCode = httpException.GetHttpCode(); if (errorCode == 400 || errorCode == 404) { Response.StatusCode = 404; Response.Redirect(string.Format("~/ErrorPage/Index/404"), true); Server.ClearError(); return; } } var postData = string.Empty; try { using (System.IO.Stream stream = Request.InputStream) { using (System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8)) { postData = streamReader.ReadToEnd(); } } } catch { } //此处可写日志 Response.StatusCode = 500; Response.Redirect(string.Format("~/ErrorPage/Index/500"), true); Server.ClearError(); } }
2、新建控制器
public class ErrorPageController : Controller { // // GET: /ErrorPage/ public ActionResult Index(int id) { ViewBag.ErrorCode = id; return View(); } }
3、路由要有如下的路由,保证能正确找到方法,只要保证能正确找到方法,路由并无限制
routes.MapRoute( name: "Default6", url: "{controller}/{action}/{id}", defaults: new { culture = cul, controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new string[] { "AiAn.GPS.Web.Controllers" } );
4、根目录下的web.config 设置customError为off 一般默认为off
<customErrors mode="Off"> </customErrors>
5、注释filterConfig.cs中的系统错误处理代码
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); }