日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

ASP.NET Core Filter如何支持依赖注入

發布時間:2023/12/4 asp.net 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET Core Filter如何支持依赖注入 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

概述

通過使用 ASP.NET Core 中的篩選器,可在請求處理管道中的特定階段之前或之后運行代碼。內置篩選器處理任務,例如:授權(防止用戶訪問未獲授權的資源)。響應緩存(對請求管道進行短路出路,以便返回緩存的響應)。可以創建自定義篩選器,用于處理橫切關注點。?橫切關注點的示例包括錯誤處理、緩存、配置、授權和日志記錄。?篩選器可以避免復制代碼。?例如,錯誤處理異常篩選器可以合并錯誤處理。

ASP.NET Core Filter如何支持依賴注入?可以通過全局注冊,支持依賴注入。通過TypeFilter(typeof(Filter)) 標記在方法,標記在控制器。通過ServiceType(typeof(Filter))標記在方法,標記在控制器,必須要注冊Filter這類;TypeFilter和ServiceType的本質是實現了一個IFilterFactory接口;

代碼實現

1、普通Filter使用,繼承: Attribute, IActionFilter。

public class TestActionFilterAttribute : Attribute, IActionFilter{public void OnActionExecuted(ActionExecutedContext context){if (context.HttpContext.Request.Query.TryGetValue("id", out StringValues value)){Console.WriteLine(value.First());}else{context.HttpContext.Response.Redirect("/Error/404");}}public void OnActionExecuting(ActionExecutingContext context){ }} [TestActionFilter]public IActionResult Index(){return View();}

2、使用 ?[TypeFilter(typeof(TestActionFilterAttribute))]注入。

public class TestActionFilterAttribute : Attribute, IActionFilter{private readonly ILogger _logger;public TestActionFilterAttribute(ILoggerFactory logger){_logger = logger.CreateLogger("TestActionFilterAttribute");}public void OnActionExecuted(ActionExecutedContext context){_logger.LogDebug($"11111");if (context.HttpContext.Request.Query.TryGetValue("id", out StringValues value)){Console.WriteLine(value.First());}else{context.HttpContext.Response.Redirect("/Error/404");}}public void OnActionExecuting(ActionExecutingContext context){ }} [TypeFilter(typeof(TestActionFilterAttribute))]public IActionResult Index(){return View();}

3、使用 [ServiceFilter(typeof(TestActionFilterAttribute))]注入。

[ServiceFilter(typeof(TestActionFilterAttribute))]public IActionResult Index(){return View();}

運行測試,發現報錯

于是ConfigureServices加上services.AddSingleton<TestActionFilterAttribute>();

// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddSingleton<TestActionFilterAttribute>();services.AddControllersWithViews();}

運行測試,成功。

4、通過全局注冊

public void ConfigureServices(IServiceCollection services){// services.AddSingleton<TestActionFilterAttribute>();services.AddControllersWithViews(options =>{// 添加全局異常options.Filters.Add<TestActionFilterAttribute>();});}

代碼地址:

https://gitee.com/conanOpenSource_admin/service-filter_-type-filter

總結

以上是生活随笔為你收集整理的ASP.NET Core Filter如何支持依赖注入的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。