ASP.NET Core MVC中的Filter作用是在请求处理管道的某些阶段之前或之后可以运行特定的代码。

Filter特性在之前的ASP.NET MVC中已经出现,但过去只有Authorization,Exception,Action,Result四种类型,现在又增加了一种Resource类型。所以共计五种。

Resource类型Filter在Authorization类型Filter之后执行,但又在其它类型的Filter之前。且执行顺序也在Model Binding之前,所以可以对Model Binding产生影响。

ASP.NET Core MVC框架中可以看到有ConsumesAttribute及FormatFilter两种实现IResourceFilter接口的类。

ConsumesAttribute会按请求中的Content-Type(内容类型)进行过滤,而FormatFilter能对路由或路径中设置了format值的请求作过滤。

一旦不符合要求,就对ResourceExecutingContext的Result属性设置,这样可以达到短路效果,阻止进行下面的处理。

ConsumesAttribute类的例子:

  1. public void OnResourceExecuting(ResourceExecutingContext context)
  2. {
  3. ...
  4. // Only execute if the current filter is the one which is closest to the action.
  5. // Ignore all other filters. This is to ensure we have a overriding behavior.
  6. if (IsApplicable(context.ActionDescriptor))
  7. {
  8. var requestContentType = context.HttpContext.Request.ContentType;
  9. // Confirm the request's content type is more specific than a media type this action supports e.g. OK
  10. // if client sent "text/plain" data and this action supports "text/*".
  11. if (requestContentType != null && !IsSubsetOfAnyContentType(requestContentType))
  12. {
  13. context.Result = new UnsupportedMediaTypeResult();
  14. }
  15. }
  16. }

Filter在ASP.NET Core MVC里除了保留原有的包含同步方法的接口,现在又增加了包含异步方法的接口。

同步

  • IActionFilter
  • IAuthorizationFilter
  • IExceptionFilter
  • IResourceFilter
  • IResultFilter

异步

  • IAsyncActionFilter
  • IAsyncAuthorizationFilter
  • IAsyncExceptionFilter
  • IAsyncResourceFilter
  • IAsyncResultFilter

新的接口不像旧有的接口包含两个同步方法,它们只有一个异步方法。但可以实现同样的功能。

  1. public class SampleAsyncActionFilter : IAsyncActionFilter
  2. {
  3. public async Task OnActionExecutionAsync(
  4. ActionExecutingContext context,
  5. ActionExecutionDelegate next)
  6. {
  7. // 在方法处理前执行一些操作
  8. var resultContext = await next();
  9. // 在方法处理后再执行一些操作。
  10. }
  11. }

Attribute形式的Filter,其构造方法里只能传入一些基本类型的值,例如字符串:

  1. public class AddHeaderAttribute : ResultFilterAttribute
  2. {
  3. private readonly string _name;
  4. private readonly string _value;
  5. public AddHeaderAttribute(string name, string value)
  6. {
  7. _name = name;
  8. _value = value;
  9. }
  10. public override void OnResultExecuting(ResultExecutingContext context)
  11. {
  12. context.HttpContext.Response.Headers.Add(
  13. _name, new string[] { _value });
  14. base.OnResultExecuting(context);
  15. }
  16. }
  17. [AddHeader("Author", "Steve Smith @ardalis")]
  18. public class SampleController : Controller

如果想要在其构造方法里引入其它类型的依赖,现在可以使用ServiceFilterAttribute,TypeFilterAttribute或者IFilterFactory方式。

ServiceFilterAttribute需要在DI容器中注册:

  1. public class GreetingServiceFilter : IActionFilter
  2. {
  3. private readonly IGreetingService greetingService;
  4. public GreetingServiceFilter(IGreetingService greetingService)
  5. {
  6. this.greetingService = greetingService;
  7. }
  8. public void OnActionExecuting(ActionExecutingContext context)
  9. {
  10. context.ActionArguments["param"] =
  11. this.greetingService.Greet("James Bond");
  12. }
  13. public void OnActionExecuted(ActionExecutedContext context)
  14. { }
  15. }
  16. services.AddScoped<GreetingServiceFilter>();
  17. [ServiceFilter(typeof(GreetingServiceFilter))]
  18. public IActionResult GreetService(string param)

TypeFilterAttribute则没有必要:

  1. public class GreetingTypeFilter : IActionFilter
  2. {
  3. private readonly IGreetingService greetingService;
  4. public GreetingTypeFilter(IGreetingService greetingService)
  5. {
  6. this.greetingService = greetingService;
  7. }
  8. public void OnActionExecuting(ActionExecutingContext context)
  9. {
  10. context.ActionArguments["param"] = this.greetingService.Greet("Dr. No");
  11. }
  12. public void OnActionExecuted(ActionExecutedContext context)
  13. { }
  14. }
  15. [TypeFilter(typeof(GreetingTypeFilter))]
  16. public IActionResult GreetType1(string param)

IFilterFactory也是不需要的:

  1. public class GreetingFilterFactoryAttribute : Attribute, IFilterFactory
  2. {
  3. public bool IsReusable => false;
  4. public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
  5. {
  6. var logger = (IGreetingService)serviceProvider.GetService(typeof(IGreetingService));
  7. return new GreetingFilter(logger);
  8. }
  9. private class GreetingFilter : IActionFilter
  10. {
  11. private IGreetingService _greetingService;
  12. public GreetingFilter(IGreetingService greetingService)
  13. {
  14. _greetingService = greetingService;
  15. }
  16. public void OnActionExecuted(ActionExecutedContext context)
  17. {
  18. }
  19. public void OnActionExecuting(ActionExecutingContext context)
  20. {
  21. context.ActionArguments["param"] = _greetingService.Greet("Dr. No");
  22. }
  23. }
  24. }
  25. [GreetingFilterFactory]
  26. public IActionResult GreetType1(string param)

Filter有三种范围:

  • Global
  • Controller
  • Action

后两种可以通过Attribute的方式附加到特定Action方法或者Controller类之上。对于Global,则要在ConfigureServices方法内部添加。

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddMvc(options =>
  4. {
  5. // by instance
  6. options.Filters.Add(new AddDeveloperResultFilter("Tahir Naushad"));
  7. // by type
  8. options.Filters.Add(typeof(GreetDeveloperResultFilter));
  9. });
  10. }

顾名思义,Global将对所有Controller及Action产生影响。所以务必对其小心使用。

这三种范围的执行顺序在设计程序的时候也需要多作考虑:

  1. Global范围的前置处理代码
  2. Controller范围的前置处理代码
  3. Action范围的前置处理代码
  4. Action范围的后置处理代码
  5. Controller范围的后置处理代码
  6. Global范围的后置处理代码

典型的前置处理代码如常见的OnActionExecuting方法,而常见的后置处理代码,则是像OnActionExecuted方法这般的。

.NET Core开发日志——Filter的更多相关文章

  1. .NET Core开发日志——Entity Framework与PostgreSQL

    Entity Framework在.NET Core中被命名为Entity Framework Core.虽然一般会用于对SQL Server数据库进行数据操作,但其实它还支持其它数据库,这里就以Po ...

  2. .NET Core开发日志——RequestDelegate

    本文主要是对.NET Core开发日志--Middleware的补遗,但是会从看起来平平无奇的RequestDelegate开始叙述,所以以其作为标题,也是合情合理. RequestDelegate是 ...

  3. C#实现多级子目录Zip压缩解压实例 NET4.6下的UTC时间转换 [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程 asp.net core异步进行新增操作并且需要判断某些字段是否重复的三种解决方案 .NET Core开发日志

    C#实现多级子目录Zip压缩解压实例 参考 https://blog.csdn.net/lki_suidongdong/article/details/20942977 重点: 实现多级子目录的压缩, ...

  4. .NET Core开发日志——从搭建开发环境开始

    .NET Core自2016年推出1.0版本开始,到目前已是2.1版本,在其roadmap计划里明年更会推出3.0版本,发展不可不谓之迅捷.不少公司在经过一个谨慎的观望期后,也逐步开始将系统升级至最新 ...

  5. .NET Core开发日志——Model Binding

    ASP.NET Core MVC中所提供的Model Binding功能简单但实用,其主要目的是将请求中包含的数据映射到action的方法参数中.这样就避免了开发者像在Web Forms时代那样需要从 ...

  6. .NET Core开发日志——OData

    简述 OData,即Open Data Protocol,是由微软在2007年推出的一款开放协议,旨在通过简单.标准的方式创建和使用查询式及交互式RESTful API. 类库 在.NET Core中 ...

  7. .NET Core开发日志——结构化日志

    在.NET生态圈中,最早被广泛使用的日志库可能是派生自Java世界里的Apache log4net.而其后来者,莫过于NLog.Nlog与log4net相比,有一项较显著的优势,它支持结构化日志. 结 ...

  8. .NET Core开发日志——Edge.js

    最近在项目中遇到这样的需求:要将旧有系统的一部分业务逻辑集成到新的自动化流程工具中.这套正在开发的自动化工具使用的是C#语言,而旧有系统的业务逻辑则是使用AngularJS在前端构建而成.所以最初的考 ...

  9. .NET Core开发日志——Linux版本的SQL Server

    SQL Server 2017版本已经可以在Linux系统上安装,但我在尝试.NET Core跨平台开发的时候使用的是Mac系统,所以这里记录了在Mac上安装SQL Server的过程. 最新的SQL ...

随机推荐

  1. pycharm如何解决新建的文件没有后缀的问题

    如下设置: 1.settings 2.file and code templates3.点击图中绿色的“+”号,即可打开新建模板页面4.定义模板名字.后缀名保存即可

  2. 3728 联合权值[NOIP 2014 Day1 T2]

    来源:NOIP2014 Day1 T2 OJ链接: http://codevs.cn/problem/3728/ https://www.luogu.org/problemnew/show/P1351 ...

  3. ubuntu下解压文件命令大全(转)

    ubuntu 下rar解压工具安装方法: 压缩功能 安装 sudo apt-get install rar卸载 sudo apt-get remove rar 解压功能 安装 sudo apt-get ...

  4. C#通过DSOFile读取与修改文件的属性

    搜了一圈用C#读取与修改文件属性的文章,结果几乎找不到- -: 偶然间看到一个DSOFile工具,然后找到了对该工具进行详细讲解的一篇文章:<DSOfile,一个修改windows系统文件摘要的 ...

  5. CPP Note

    hello.cpp -> 编译代码g++ hello.cpp -o a -> a.out 区分大小写的编程语言 内置类型 一些基本类型可以使用一个或多个类型修饰符进行修饰: signed: ...

  6. android异步向服务器请求数据

    下面就android向服务器请求数据的问题分析如下: 1.在android4.0以后的版本,主线程(UI线程)不在支持网络请求,原因大概是影响主线程,速度太慢,容易卡机,所以需要开启新的线程请求数据: ...

  7. c#实现windows远程桌面连接程序代码

    使用winform制作windows远程桌面连接程序,windows自带了远程桌面连接,我们需要将远程桌面连接集成 到自己的winform程序,并实现管理远程主机的配置. 远程桌面核心类库 windo ...

  8. Java编程的逻辑 (77) - 异步任务执行服务

    ​本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http: ...

  9. A Tour of ParallelExtensionsExtras

    Throughout the development of Parallel Extensions for the .NET Framework 4, we've come across a myri ...

  10. L1&L2 Regularization的原理

    L1&L2 Regularization   正则化方法:防止过拟合,提高泛化能力 在训练数据不够多时,或者overtraining时,常常会导致overfitting(过拟合).其直观的表现 ...