[英]Global filters with parameter dependencies in .net core 5
I have a validation filter.我有一个验证过滤器。 I want to register it as global level.我想将其注册为全球级别。 But in the ConfigureServices method i can not assign the dependencies of it.但是在 ConfigureServices 方法中,我无法分配它的依赖项。 Is there any efficient way to do it.有没有什么有效的方法来做到这一点。 Here is my code.这是我的代码。
My filter.我的过滤器。
public class ModelValidationFilterAttribute : Attribute, IAsyncActionFilter
{
public ILogger<ModelValidationFilterAttribute> logger { get; }
public ModelValidationFilterAttribute(ILogger<ModelValidationFilterAttribute> logger)
{
this.logger = logger;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
await next.Invoke();
}
}
Extension method扩展方法
public static IServiceCollection CustomServices(this IServiceCollection services)
{
services.AddScoped<ModelValidationFilterAttribute>();
return services;
}
In ConfigureServices method在 ConfigureServices 方法中
public void ConfigureServices(IServiceCollection services)
{
services.CustomServices();
services.AddControllers(options =>
{
options.Filters.Add(new ModelValidationFilterAttribute());
});
}
Code works fine if i register it on controller or action level with attribute.如果我在 controller 或具有属性的操作级别上注册代码,代码工作正常。 But when i try to register it on service level it doesn't take the argument.但是当我尝试在服务级别注册它时,它不会接受这个论点。
Instead of adding this as a filter, add a filter as service.不要将此添加为过滤器,而是将过滤器添加为服务。 It will do the magic.它会变魔术。
options.Filters.AddService<ModelValidationFilterAttribute>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.