如何在 ASP.NET Core 中使用 ActionFilter

ASP.NET Core MVC 中的 Filters 允許我們在 請求處理管道 中的某一個階段的之前和之後執行自定義代碼,不同類型的 filter 對應着 請求處理管道 的不同階段,比如說:ActionFilter 可以在 Action 方法的之前或者之後執行自定義代碼,這篇文章我們就來討論 ASP.NET Core MVC 中內建的 ActionFilter,爲什麼它非常有用以及在程序中如何使用它。

Filter 過濾器

其實在 ASP.NET Core MVC 中有很多的內建 filter,大體羅列如下:

  • ActionFilters

它會在 Action 方法的執行前和執行後 執行。

  • AuthorizationFilters

它會在 請求處理管道 的開始處被執行,主要用來獲取用戶的 憑證信息 來驗證用戶是否被授權。

  • ResourceFilters

它會在 authorization 之後 和 模型綁定 之前被執行,可以利用它實現一些緩存邏輯。

  • ExceptionFilters

它會捕捉到 請求處理管道 中的所有異常,所以可用它來實現一些自定義的異常處理。

到底用哪一種類型的 filter,還是取決於你到底想實現什麼業務,舉個例子,如果你想 短路 request,提前結束 pipeline 管道返回結果,是不是就可以用 ResourceFilters 哈,再舉一個例子,如果你想修改 Action 的入參 並且想對 Action 的結果進行修改,那麼 ActionFilter 就是你的最佳選擇。

ASP.NET Core MVC 中有一個特性叫 ActionFilterAttribute,它實現瞭如下接口 IActionFilter, IAsyncActionFilter, IResultFilter, IAsyncResultFilter, IOrderedFilter,可以利用它實現不同層級的Filter,如:Action級,Controller級,全局級,稍後我們將會一一討論。

創建自定義的 ActionFilter

你可以利用自定義的 ActionFilter 在 Action 方法的前後執行一些可複用的邏輯,或許大家都知道,這就是所謂的 AOP 編程,除了 ActionFilterAttribute ,還有其他幾個 Filter 也有類似的 Attribute。

  • ResultFilterAttribute

  • ExceptionFilterAttribute

  • ServiceFilterAttribute

  • TypeFilterAttribute

除了上面這些快捷特性,最簡單粗暴的就是實現 IActionFilter 接口 ,還可以實現 同步異步 雙模式。

創建同步的 ActionFilter

下面的代碼片段展示瞭如何創建同步模式的 ActionFilter,繼承 IActionFilter 接口並實現它的 OnActionExecutingOnActionExecuted 兩個方法。


    public class SimpleActionFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //this method will be executed before execution of an action method 
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //this method will be executed after an action method has executed 
        }
    }

創建異步模式的 ActionFilter

下面的代碼片段展示瞭如何創建異步模式的 ActionFilter,繼承 IAsyncActionFilter 接口並實現它的 OnActionExecutionAsync 方法。


    public class SimpleAsyncActionFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context,
          ActionExecutionDelegate next)
        {
            //code written here will be executed before execution of an action method 
            await next();
            //code written here will be executed after execution of an action method 
        }
    }

配置 ActionFilter

文章之前也說過了,可以將 filter 過濾器 添加到不同級別的作用域中,這些作用域包括:action級, controller級,global級,這裏就來演示如何將 filter 添加到 global級 ,仔細觀察一下我的 自定義filter 是如何添加到 ConfigureServices 方法下的 filter集合 中,如下代碼所示:


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add(new SimpleAsyncActionFilter());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

除了上面的方法,還可以用 typeof 的方式加入到 options 中,如下代碼所示:


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(SimpleAsyncActionFilter));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

總結一下:過濾器允許我們在 請求處理管道 中的某一個點的前後執行一些自定義代碼,而且 ActionFilter 還有一個非常大的新改進是可以在 Http 請求管道中指定過濾器的執行順序,關於更多的 filter 的高級特性,我會在後面的文章中和大家一起分享。

譯文鏈接:https://www.infoworld.com/article/3328648/how-to-use-action-filters-in-aspnet-core-mvc.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章