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

DotNetCore实战

共 3446字,需浏览 7分钟

 · 2021-03-28


概述

通过使用 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


往期精彩回顾




【推荐】.NET Core开发实战视频课程 ★★★

.NET Core实战项目之CMS 第一章 入门篇-开篇及总体规划

【.NET Core微服务实战-统一身份认证】开篇及目录索引

Redis基本使用及百亿数据量中的使用技巧分享(附视频地址及观看指南)

.NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了

10个小技巧助您写出高性能的ASP.NET Core代码

用abp vNext快速开发Quartz.NET定时任务管理界面

在ASP.NET Core中创建基于Quartz.NET托管服务轻松实现作业调度

现身说法:实际业务出发分析百亿数据量下的多表查询优化

关于C#异步编程你应该了解的几点建议

C#异步编程看这篇就够了


浏览 33
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报