.NET Core开发日志——Filter

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类的例子:

public void OnResourceExecuting(ResourceExecutingContext context)
{
    ...

    // Only execute if the current filter is the one which is closest to the action.
    // Ignore all other filters. This is to ensure we have a overriding behavior.
    if (IsApplicable(context.ActionDescriptor))
    {
        var requestContentType = context.HttpContext.Request.ContentType;

        // Confirm the request‘s content type is more specific than a media type this action supports e.g. OK
        // if client sent "text/plain" data and this action supports "text/*".
        if (requestContentType != null && !IsSubsetOfAnyContentType(requestContentType))
        {
            context.Result = new UnsupportedMediaTypeResult();
        }
    }
}

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

同步

  • IActionFilter
  • IAuthorizationFilter
  • IExceptionFilter
  • IResourceFilter
  • IResultFilter

异步

  • IAsyncActionFilter
  • IAsyncAuthorizationFilter
  • IAsyncExceptionFilter
  • IAsyncResourceFilter
  • IAsyncResultFilter

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

public class SampleAsyncActionFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(
        ActionExecutingContext context,
        ActionExecutionDelegate next)
    {
        // 在方法处理前执行一些操作
        var resultContext = await next();
        // 在方法处理后再执行一些操作。
    }
}

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

public class AddHeaderAttribute : ResultFilterAttribute
{
    private readonly string _name;
    private readonly string _value;

    public AddHeaderAttribute(string name, string value)
    {
        _name = name;
        _value = value;
    }

    public override void OnResultExecuting(ResultExecutingContext context)
    {
        context.HttpContext.Response.Headers.Add(
            _name, new string[] { _value });
        base.OnResultExecuting(context);
    }
}

[AddHeader("Author", "Steve Smith @ardalis")]
public class SampleController : Controller

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

ServiceFilterAttribute需要在DI容器中注册:

public class GreetingServiceFilter : IActionFilter
{
    private readonly IGreetingService greetingService;

    public GreetingServiceFilter(IGreetingService greetingService)
    {
        this.greetingService = greetingService;
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        context.ActionArguments["param"] =
            this.greetingService.Greet("James Bond");
    }

    public void OnActionExecuted(ActionExecutedContext context)
    { }
}

services.AddScoped<GreetingServiceFilter>();

[ServiceFilter(typeof(GreetingServiceFilter))]
public IActionResult GreetService(string param)

TypeFilterAttribute则没有必要:

public class GreetingTypeFilter : IActionFilter
{
    private readonly IGreetingService greetingService;

    public GreetingTypeFilter(IGreetingService greetingService)
    {
        this.greetingService = greetingService;
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        context.ActionArguments["param"] = this.greetingService.Greet("Dr. No");
    }

    public void OnActionExecuted(ActionExecutedContext context)
    { }
}

[TypeFilter(typeof(GreetingTypeFilter))]
public IActionResult GreetType1(string param)

IFilterFactory也是不需要的:

public class GreetingFilterFactoryAttribute : Attribute, IFilterFactory
{
    public bool IsReusable => false;

    public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
    {
        var logger = (IGreetingService)serviceProvider.GetService(typeof(IGreetingService));
        return new GreetingFilter(logger);
    }

    private class GreetingFilter : IActionFilter
    {
        private IGreetingService _greetingService;
        public GreetingFilter(IGreetingService greetingService)
        {
            _greetingService = greetingService;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            context.ActionArguments["param"] = _greetingService.Greet("Dr. No");
        }
    }
    }

[GreetingFilterFactory]
public IActionResult GreetType1(string param)

Filter有三种范围:

  • Global
  • Controller
  • Action

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

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        // by instance
        options.Filters.Add(new AddDeveloperResultFilter("Tahir Naushad"));

        // by type
        options.Filters.Add(typeof(GreetDeveloperResultFilter));
    });

}

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

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

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

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

原文地址:https://www.cnblogs.com/kenwoo/p/9532317.html

时间: 2024-08-01 15:37:11

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

.NET Core开发日志——RequestDelegate

本文主要是对.NET Core开发日志--Middleware的补遗,但是会从看起来平平无奇的RequestDelegate开始叙述,所以以其作为标题,也是合情合理. RequestDelegate是一种委托类型,其全貌为public delegate Task RequestDelegate(HttpContext context),MSDN上对它的解释,"A function that can process an HTTP request."--处理HTTP请求的函数.唯一参数,

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

Entity Framework在.NET Core中被命名为Entity Framework Core.虽然一般会用于对SQL Server数据库进行数据操作,但其实它还支持其它数据库,这里就以PostgreSQL作为例子. PostgreSQL PostgreSQL可以选用原生系统与Docker两种安装方式. Official Docker Package 在应用程序工程中添加相关的引用. dotnet add package Npgsql.EntityFrameworkCore.Postg

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

.Net Core自2016年推出1.0版本开始,到目前已是2.1版本,在其roadmap计划里明年更会推出3.0版本,发展不可不谓之迅捷.不少公司在经过一个谨慎的观望期后,也逐步开始将系统升级至最新的.Net Core平台,所以现在开始进行.Net Core开发可谓正当其时. 因为.Net Core支持Windows系统以外的Linux与Mac系统,在选择开发环境时,并不需要局限在原有的Windows平台,这里我选用了Mac平台. 开发硬件设备是一台14年款的Apple Macbook Air

.NET Core开发日志——Model Binding

ASP.NET Core MVC中所提供的Model Binding功能简单但实用,其主要目的是将请求中包含的数据映射到action的方法参数中.这样就避免了开发者像在Web Forms时代那样需要从Request类中手动获取数据的繁锁操作,直接提高了开发效率.此功能继承自ASP.NET MVC,所以熟悉上一代框架开发的工程师,可以毫无障碍地继续享有它的便利. 本文想要探索下Model Binding相关的内容,这里先从源码中找到其发生的时机与场合. 在ControllerActionInvok

.Net Core开发日志——Peachpie

.Net Core的生态圈随着开源社区的力量不断注入至其中,正在变得越来越强盛,并且不时得就出现些有意思的项目,比如Peachpie,它使得PHP的代码迁移到.Net Core项目变得可能. 从创建简单的入门程序开始可以更容易地体会其特性. 首先安装Peachpie的模板: dotnet new -i Peachpie.Templates::* 接着创建项目: dotnet new web -lang PHP -o helloPHP 然后切换目录至Server文件夹运行程序: cd Server

.NET Core开发日志——Startup

一个典型的ASP.NET Core应用程序会包含Program与Startup两个文件.Program类中有应用程序的入口方法Main,其中的处理逻辑通常是创建一个WebHostBuilder,再生成WebHost,最后启动之. 而在创建WebHostBuilder时又会常常会指定一个Startup类型. public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilde

.NET Core开发日志——简述路由

有过ASP.NET或其它现代Web框架开发经历的开发者对路由这一名字应该不陌生.如果要用一句话解释什么是路由,可以这样形容:通过对URL的解析,指定相应的处理程序. 回忆下在Web Forms应用程序中使用路由的方式: public static void RegisterRoutes(RouteCollection routes) { routes.MapPageRoute("", "Category/{action}/{categoryName}", "

.NET Core开发日志——Controller

在理清路由的工作流程后,接下来需要考虑的,是MVC框架如何生成Controller以及它的生成时机. 根据以前ASP.NET MVC的经验,Controller应该是由一个ControllerFactory构建的.查看ASP.NET Core MVC的源码,果然是有一个DefaultControllerFactory类,并且不出意外的,它拥有一个CreateController方法. public virtual object CreateController(ControllerContext

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

SQL Server 2017版本已经可以在Linux系统上安装,但我在尝试.NET Core跨平台开发的时候使用的是Mac系统,所以这里记录了在Mac上安装SQL Server的过程. 最新的SQL Server没有专门为Mac系统准备安装包,但由于Mac系统上支持Docker,所以可以用一种变通的方式--在Docker内部安装Linux版本的SQL Server. 系统要求 因为我的Macbook Air型号比较老,硬件条件很一般,所以首先确定下是否满足安装SQL Server的条件.官方给