1全局注册
2ServiceFilter (要记得ConfigureService)
3TypeFilte
对于ActionFilter这类有进有出的filter
执行顺序 全局Executing->控制器Executing->Action的Executing->Action的Executed->控制器Executed->全局Executed
1全局注册
public class ExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { if (!context.ExceptionHandled) { Console.WriteLine($"你没处理列{context.HttpContext.Request.Path}{context.Exception.Message}"); context.Result = new JsonResult(new { Result = false, Msg = "异常,请联系管理员" }); context.ExceptionHandled = true;//表示异常已经处理 } } } //然后在Startup的ConfigureServices中注册 public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews( s => { s.Filters.Add(typeof(ExceptionFilter)); } ); }
还可以定义ExceptionFilterAttribute自己决定放在全局、控制器、Action方法
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute { /// <summary> /// 当异常的发生时会进来 /// </summary> /// <param name="context"></param> public override void OnException(ExceptionContext context) { if (!context.ExceptionHandled) { Console.WriteLine($"你没处理列{context.HttpContext.Request.Path}{context.Exception.Message}"); context.Result = new JsonResult(new { Result=false,Msg="异常,请联系管理员"}); context.ExceptionHandled = true;//表示异常已经处理 } } }
Filter特性放在Action方法上给该Action方法注册
[CustomExceptionFilterAttribute] public IActionResult Index()
给控制器注册
[CustomExceptionFilterAttribute] public class AopController : Controller
全局注册
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews( s => { s.Filters.Add(typeof(CustomExceptionFilterAttribute));//全局注册 //s.Filters.Add(typeof(ExceptionFilter)); } ); }
2 ServiceFilter (要记得ConfigureService)
[ServiceFilter(typeof(CustomExceptionFilterAttribute))] public IActionResult Index()
//在ConfigureServices中单独注册 services.AddSingleton<CustomExceptionFilterAttribute>();
3TypeFilter
[TypeFilter(typeof(CustomExceptionFilterAttribute))] public IActionResult Index()