Net Core教程

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

 

这篇关于ASP.NET Core Filter如何支持依赖注入的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!