使用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为空,可以跳转我们默认制定的主页
//自定义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串,具体代码和效果如下
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; } }