ASP.NET Core Filter支持依赖注入

过滤器可以通过全局注册,支持依赖注入

TypeFilter

需要传入类型参数

    public sealed class AuthorizeAdminAttribute : TypeFilterAttribute
    {
        public AuthorizeAdminAttribute(bool ignore = false) 
        :base(typeof(AuthorizeAdminFilter))
        {
            IgnoreFilter = ignore;
            Arguments = new object[] { ignore };
        }

        /// 
        /// 获取一个值指示是否忽略过滤器动作的执行
        /// 
        public bool IgnoreFilter { get; }

        private class AuthorizeAdminFilter : IAsyncAuthorizationFilter
        {
            private readonly bool _ignoreFilter;

            private readonly ILogger _logger;

            public AuthorizeAdminFilter(bool ignoreFilter,         
             ILoggerlogger)
            {
                _logger = logger;
                _ignoreFilter = ignoreFilter;
            }

            public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
            {
                await Task.CompletedTask;
            }
        }
    }

Arguments是设置自定义注入的对象 key 以Filter结尾,列如:ignoreFilter

控制器代码


        [AuthorizeAdmin]
        public IActionResult Index()
        {
            return View();
        }

ServiceType

与TypeFilter使用流程不一样,传入的type类型参数 必须要注册Filter这类

    public sealed class ValidateIpAddressAttribute : ServiceFilterAttribute
    {
        public ValidateIpAddressAttribute() : base(typeof(ValidateIpAddressFilter))
        {
        }

        public class ValidateIpAddressFilter : IAsyncActionFilter
        {
            private readonly ILogger _logger;

            public ValidateIpAddressFilter(ILogger logger)
            {
                _logger = logger;
            }

            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                await next();
            }
        }
    }

控制器代码

        [ValidateIpAddress]
        public IActionResult Index()
        {
            return View();
        }

必须将该过滤器注册值IOC容器中,否则会报错

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton();
        }

TypeFilter和ServiceType的本质是实现了一个IFilterFactory接口

你可能感兴趣的:(.net,Core,asp.net,core,c#)