使用NerCore开发框架过程当中须要对404,500等状态码进行友好提示页面处理,参照asp.net mvc并无发现提供Application_Error和Application_BeginRequest方法,是用拦截器路由不匹配的状况下也不会进行拦截,但NetCore中在Microsoft.AspNetCore.Builder.UseExtensions中提供了Use扩展方法对HttpContext进行了拦截处理,这样咱们就能够获取到Request和Response针对跳转进行处理,咱们在Startup的Configure方法中加入以下代码,在404的状况同时能够处理访问项目时的默认路由跳转,例如访问http://localhost:4099/fastcloud时不加入具体主页面路由,则context.Request.Path为空,能够跳转咱们默认制定的主页mvc
//自定义404和500处理 app.Use(async (context, next) => { await next(); if (context.Response.StatusCode == 404) { string FilePath = context.Request.Path; if (string.IsNullOrEmpty(FilePath) || FilePath == "/") { context.Request.Path = "/" + AppConfigUtil.Configuration["Frame:DefaultHomeUrl"]; } else { context.Request.Path = "/frame/home/error/404"; } await next(); } if (context.Response.StatusCode == 500) { context.Request.Path = "/frame/home/error/500"; } });
须要注意的是,若是在项目中加入的全局异常拦截器,则须要判断若是是页面请求,才会跳转至自定义500页面,Ajax请求返回错误的Json串,具体代码和效果以下app
public class GlobalExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { string FloderPath = CloudUtil.GetContentPath() + "/Logs"; DirectoryInfo SystemLogDir = new DirectoryInfo(FloderPath); if (!SystemLogDir.Exists) { SystemLogDir.Create(); } StringBuilder builder = new StringBuilder(); builder.AppendFormat("异常请求url:{0}", context.HttpContext.Request.Path + Environment.NewLine); builder.AppendFormat("异常信息:{0}", context.Exception.Message + Environment.NewLine); builder.AppendFormat("堆栈信息:{0}", context.Exception.StackTrace + Environment.NewLine); LogUtil.WriteLog(CloudUtil.GetContentPath() + "/Logs/Exception", "log_", builder.ToString()); bool IsAjaxCall = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest"; if (IsAjaxCall) { context.Result = Result.Error("系统发生错误,请联系管理员!"); context.ExceptionHandled = true; } else { context.Result = new RedirectResult(CloudUtil.GetRootPath() + "frame/home/error/500"); context.ExceptionHandled = true; } }