我已经实现了一个类的IAsyncAuthorizationFilter
接口(interface);此外,该类派生自 Attribute
,因此我可以使用它来标记 Controller 类和操作方法。到目前为止,这是有效的; Task OnAuthorizationAsync(AuthorizationFilterContext context)
方法在 action 方法之前调用,如果请求未通过身份验证,则返回 HTTP 401
作为响应。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class CustomAuthenticationAttribute : Attribute, IAsyncAuthorizationFilter
{
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
...
}
}
这个属性使用如下...
[CustomAuthenticationAttribute]
public class SomeDataController : Controller
{
[HttpGet]
public async Task GetData()
{
...
}
}
现在,我想使用一个应用程序服务(它从数据库中获取身份验证所需的 secret 私钥信息)并尝试为此使用属性注入(inject)。通过 ctor 注入(inject)依赖在这里不是一个好的选择,因为它是作为一个属性实现的。所以我尝试...
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class CustomAuthenticationAttribute : Attribute, IAsyncAuthorizationFilter
{
public IPrivateKeyLookupService KeyService { get; set; }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
string publicKey = ...
...
var privateKey = await this.KeyService.GetPrivateKeyFrom(publicKey);
...
}
}
...但是属性注入(inject)在这里似乎不起作用。该服务已向 IoC 注册,但属性未连接。这是一个 ASP.NET Core 1.1 项目,我在其中使用 Autofac
。在 Startup
类中,我的 ConfigureServices
方法有类似的东西......
public void ConfigureServices(IServicesCollection collection)
{
...
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<AuthKeyService>().As<IPrivateKeyLookupService>();
containerBuilder.Populate(services);
this.container = containerBuilder.Build();
}
Autofac
是否支持 IAsyncAuthorizationFilter
类型的 Autowiring ?如果没有,我如何填充该功能?
最佳答案
原来很简单...
在 ASP.NET Core
中有 TypeFilter
属性,它也是一个过滤器,它创建另一个过滤器(由 Type
指定)并满足它的构造函数参数涉及依赖注入(inject)。
我更改了 IAsyncAuthorizationFilter
的实现;删除了属性并添加了一个构造函数,因为使用 TypeFilter
构造函数注入(inject)现在可以工作......
public sealed class CustomAuthenticationAttribute : IAsyncAuthorizationFilter
{
private readonly IPrivateKeyLookupService keyService;
public CustomAuthenticationAttribute(
IPrivateKeyLookupService keyService)
{
this.keyService = keyService;
}
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
...
}
}
我还删除了 Attribute
的继承,因为不再需要它以及 AttributeUsage
属性的声明。
所以,我可以按如下方式使用我的属性...
[TypeFilter(typeof(CustomAuthenticationAttribute))]
public class SomeDataController : Controller
{
[HttpGet]
public async Task GetData()
{
...
}
}
也可以通过 TypeFilter
类的 object[] Arguments
属性将附加参数传递给过滤器的构造函数。
关于c# - 如何在 ASP.NET Core 中使用 IAsyncAuthorizationFilter 进行依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43275879/