.Net Core AOP之IExceptionFilter
作者:互联网
一、简介
在.net core 中Filter分为以下六大类:
1、AuthorizeAttribute(权限验证)
2、IResourceFilter(资源缓存)
3、IActionFilter(执行方法前后的记录)
4、IResultFilter(结果生成前后扩展)
5、IAlwaysRun(响应结果的补充)
6、IExceptionFilter(异常处理)
二、使用
public class CustomerExceptionFilterAttribute : Attribute, IExceptionFilter, IAsyncExceptionFilter { /// <summary> /// 这里分别继承了IExceptionFilter(同步)和IAsyncExceptionFilter(异步),当同步和异步都存在的时候会优先执行异步方法 /// </summary> public void OnException(ExceptionContext context) { throw new NotImplementedException(); } public Task OnExceptionAsync(ExceptionContext context) { // 判断是否是ajax请求 if(context.HttpContext.Request.Headers.ContainsKey("x-requested-with") && context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest") { context.Result = new JsonResult(new { code = "-1", success = "true" }); } else { context.HttpContext.Response.Redirect("/Home/Index"); // 页面跳转路径可自定义 } context.ExceptionHandled = true; // 表示当前异常被处理过 return Task.CompletedTask; } }
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); // 全局异常 services.AddControllers(options => { options.Filters.Add(new CustomerExceptionFilterAttribute()); }); }
标签:Core,IExceptionFilter,HttpContext,context,services,new,Net,public 来源: https://www.cnblogs.com/sportsky/p/15933939.html