1. 程式人生 > >.NET Core開發日誌——Filter

.NET Core開發日誌——Filter

data lse att 過去 tex override gets 註冊 set

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方法這般的。

.NET Core開發日誌——Filter