.net core mvc / webapi filter (FilterAttribute) dependency injection

In the .net core MVC and .net core webapi projects usually need to add filters FilterAttribute authority to deal with a number of interfaces, parameter validation problems. We need to use the filter plug-in system has been injected (class) and so on. Marked on the filter of the Controller method will not prompt us to zero argument constructor. How to deal with this problem?

The first step: injecting Filter

public void ConfigureServices(IServiceCollection services)
{ 
            //注入筛选器
            services.AddScoped<ApiActionFilterAttribute>();
}

ApiActionFilterAttribute custom of ActionFilterAttribute, inherited from ActionFilterAttribute, [Other filters can also do so]

Step two: add callouts on method


        [ServiceFilter(typeof(ApiActionFilterAttribute))]

I am here to take advantage of the ServiceFilter Microsoft has offered this service.

 

The third step: Use the registered components (plug-type)

 public class ApiActionFilterAttribute : ActionFilterAttribute
 {
        private readonly ILogger<ApiActionFilterAttribute> _logger; 
        public ApiActionFilterAttribute(Microsoft.Extensions.Options.IOptions<ILogger<ApiActionFilterAttribute> logger)
        { 
            _logger = logger;
        }
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            _logger.LogInformation(Newtonsoft.Json.JsonConvert.SerializeObject(actionContext.HttpContext.Request.Headers));
        }
}

I am here ILogger components have been implanted, you can use the component in here.

Published 12 original articles · won praise 0 · Views 653

Guess you like

Origin blog.csdn.net/oopxiajun2011/article/details/104874466