做net项目时候,在Global.asax文件中可以通过Application_Error方法全局捕获异常并处理后统一跳转到自定义的错误页面。
下面是我个人在NetCore项目中实现全局捕获异常并统一处理的功能的记录,以便备份。
1、在项目根目录新建文件夹Filter,并在文件夹下新建类,命名为GlobalExceptionFilter.cs
using Microsoft.AspNetCore.Mvc.Filters; using System; using CMSCore.Web.Core; namespace CMSCore.Web.Filter { public class GlobalExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { Exception ex = context.Exception; Log4Net.Error("系统出错", ex);//记录错误日志 context.ExceptionHandled = true; //代表异常已经处理,不会再跳转到开发调试时的异常信息页,可以跳转到我们下面自定义的方法中。若开发过程可以将
该行注释掉,则直接抛出异常调试 //通过HTTP请求头来判断是否为Ajax请求,Ajax请求的request headers里都会有一个key为x-requested-with,值“XMLHttpRequest” var requestData= context.HttpContext.Request.Headers.ContainsKey("x-requested-with"); bool IsAjax = false; if (requestData) { IsAjax = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest" ? true :false; } if(!IsAjax)//不是异步请求则跳转页面,异步请求则返回json { context.RouteData = new Microsoft.AspNetCore.Routing.RouteData(); context.RouteData.Values.Add("controller", "home"); context.RouteData.Values.Add("action", "error"); context.Result = RedirectHelper.UrlFail(context.RouteData); } else context.Result = RedirectHelper.JsonError(); } } }
2、RedirectHelper.cs的代码
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; namespace CMSCore.Web.Core { public class RedirectHelper { public static AjaxModel AjaxModel(int code,string msg,dynamic data=null,string url=null) { return new AjaxModel() { Code=code, Msg=msg, Data=data, Url=url }; } public static ActionResult JsonError() { JsonResult json = new JsonResult(AjaxModel(500, "系统出错啦")); return json; } public static ActionResult UrlFail(RouteData route) { RedirectToActionResult result = new RedirectToActionResult(route.Values["action"].ToString(), route.Values["controller"].ToString(), null); return result; } } /// <summary> /// Json返回结构 /// </summary> public class AjaxModel { public int Code { get; set; } public string Msg { get; set; } public object Data { get; set; } public string Url { get; set; } } }
3、在Startup.cs中,ConfigureServices方法添加该GlobalExceptionFilter为异常处理机制。
//记得引用对应命名空间
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //添加数据库操作上下文 services.AddDbContext<BcmfDBContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString"))); //添加全局异常处理机制 services.AddMvc(option=>{ option.Filters.Add<GlobalExceptionFilter>(); }); }