编程语言
首页 > 编程语言> > ASP.NET Core Filter如何支持依赖注入

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

作者:互联网

通过Filter来支持;分别有IResourceFilter AuthorizeFilter ActionFilter ExceptionFilter ResultFilter,Filter也被称为拦截器

 

那么 ASP.NET Core Filter如何支持依赖注入?可以通过全局注册,支持依赖注入。通过TypeFilter(typeof(Filter)) 标记在方法,标记在控制器。通过ServiceType(typeof(Filter))标记在方法,标记在控制器,必须要注册Filter这类;TypeFilter和ServiceType的本质是实现了一个IFilterFactory接口;

 

代码如下

 

   public class HomeController : Controller    {        private readonly ILoggerFactory _loggerFactory;
public HomeController(ILoggerFactory factory) { _loggerFactory = factory; }
//[TestActionFilter] // [TypeFilter(typeof(TestActionFilterAttribute))] // [ServiceFilter(typeof(TestActionFilterAttribute))] public IActionResult Index() { return View(); }
public IActionResult Privacy() { return View(); }

 

 

 

    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) { } }

 

 

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

 

标签:Core,ASP,Filter,typeof,context,TestActionFilterAttribute,logger,public
来源: https://www.cnblogs.com/yakniu/p/16669712.html