一,ActionFilterAttribute
1 public class CustomActionFilterAttribute: ActionFilterAttribute 2 { 3 public override void OnActionExecuting(ActionExecutingContext context) 4 { 5 base.OnActionExecuting(context); 6 } 7 public override void OnActionExecuted(ActionExecutedContext context) 8 { 9 base.OnActionExecuted(context); 10 } 11 12 public override void OnResultExecuting(ResultExecutingContext context) 13 { 14 base.OnResultExecuting(context); 15 } 16 17 public override void OnResultExecuted(ResultExecutedContext context) 18 { 19 base.OnResultExecuted(context); 20 } 21 }View Code
二,ExceptionFilterAttribute
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute { //出现异常处理 public override void OnException(ExceptionContext context) { //返回错误信息 context.Result = new JsonResult(new { errcode = 1, message = context.Exception.Message }); } }View Code
三,ResultFilterAttribute
public class CustomResultFilterAttribute: ResultFilterAttribute { public CustomResultFilterAttribute() { } //构造函数 //执行前 public override void OnResultExecuting(ResultExecutingContext context) { ////请求方法对象 // context.HttpContext.Response; //context.HttpContext.Request; base.OnResultExecuting(context); } //执行后 public override void OnResultExecuted(ResultExecutedContext context) { base.OnResultExecuted(context); } }View Code
四,作用域
1,Action 标识Filter
2,Controller 标识Filter
[Filters.CustomResultFilter] [Filters.CustomExceptionFilter] [Filters.CustomActionFilter] public IActionResult Index() { return View(); }
3,所有Action ,Controller
在Startup.cs 添加 options.Filters.Add(typeof(Filters.CustomeActionFilter));
public void ConfigureServices(IServiceCollection services) { services.AddRazorPages().AddRazorRuntimeCompilation(); services.AddSession();//注册Session services.AddControllersWithViews(options => { //添加筛选 options.Filters.Add(typeof(Filters.CustomeActionFilter)); }); }
五,筛选器执行-顺序设置
默认属性可以直接设置为具体int指
[Filters.CustomExceptionFilter(Order =int.MinValue)] public IActionResult Index() { return View(); }
//全局
options.Filters.Add(typeof(Filters.CustomeActionFilter),int.MaxValue);
六,ServiceFilterAttribute
Action中(CustomeActionFilter) 将从依赖注入容器DI中获取得到
public void ConfigureServices(IServiceCollection services) {
services.AddScoped<Filters.CustomeActionFilter>();
}
[ServiceFilter(typeof(Filters.CustomeActionFilter),Order =int.MaxValue)] public IActionResult Index() { return View(); }
七,TypeFilterAttribute
不需注册依赖注入,自带DI容器实现的依赖。
Microsoft.Extensions.DependencyInjection.ObjectFactory 对类型实例化
[TypeFilter(typeof(Filters.CustomeActionFilter),Order =int.MaxValue)] public IActionResult Index() { return View(); }