我尝试了以下答案:[https://stackoverflow.com/questions/18406506/custom-filter-attributes-inject-dependency][1]为Web API项目(不是MVC)实现ActionFilterAttribute(System.Web.Http.Filters) )。但是我的自定义属性从未在控制器中调用。如有任何建议,我将不胜感激。
自定义属性:
public class MyAttribute : FilterAttribute { }
筛选:
public class MyFilter : ActionFilterAttribute
{
private readonly IMyService _myService;
public MyFilter(IMyService myService)
{
_myService = myService;
}
public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
//do some with actionContext
throw new Exception("You can`t go here");
}
}
控制器方式:
[My] // Not called
[HttpPost]
[Route("/do-some")]
public async Task DoSome(string myString)
{
//do some
}
注册过滤器:
public partial class Startup
{
protected void ConfigureApi(IAppBuilder app, IContainer container)
{
var configuration = new HttpConfiguration();
//...
var serviceInstance = container.GetInstance<IMyService>();
configuration.Filters.Add(new MyFilter(serviceInstance));
}
}
这有什么问题吗?
您的代码几乎可以解决所有问题,但是您应该以其他方式注册过滤器和服务。
在Asp Net Core WebAPI中,有几种注册过滤器的方法:
全局注册示例:
services.AddControllers(options =>
{
options.Filters.Add(typeof(LoggerFilterAttribute));
});
在Controller中注册方法的示例:
我想通知您-在这种情况下,您应该使用ServiceFilter
-这有助于DI为您的过滤器解析所有依赖项。
[HttpGet]
[ServiceFilter(typeof(LoggerFilterAttribute))]
public IEnumerable<WeatherForecast> Get()
{
}
SimpleService
public interface ISimpleService
{
void Notify(string text);
}
public class SimpleService : ISimpleService
{
public void Notify(string text)
{
Console.WriteLine($"Notify from {nameof(SimpleService)}. {text}");
}
}
ActionFilterAttribute
public class LoggerFilterAttribute : ActionFilterAttribute
{
private readonly ISimpleService _simpleService;
public LoggerFilterAttribute(ISimpleService simpleService)
{
_simpleService = simpleService;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
_simpleService.Notify($"Method {nameof(OnActionExecuting)}");
}
public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
_simpleService.Notify($"Method {nameof(OnActionExecutionAsync)}");
return base.OnActionExecutionAsync(context, next);
}
}
WebAPI
DI注册来完成。 services.AddControllers(options =>
{
options.Filters.Add(typeof(LoggerFilterAttribute));
});
services.AddScoped<LoggerFilterAttribute>();
[HttpGet]
[ServiceFilter(typeof(LoggerFilterAttribute))]
public IEnumerable<WeatherForecast> Get()
{
}
services.AddTransient<ISimpleService, SimpleService>();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句