我已经将 IAsyncAuthorizationFilter
接口实现到一个类中;此外,该类派生自 Attribute
,因此我可以标记控制器类和操作方法。目前为止,这个方法是有效的;在调用操作方法之前,会调用 Task OnAuthorizationAsync(AuthorizationFilterContext context)
方法,如果请求未经过身份验证,则返回响应的 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()
{
...
}
}
现在,我想使用一个应用程序服务(从数据库中获取身份验证所需的秘密私钥信息),并尝试使用属性注入来实现。由于它是作为属性实现的,因此通过构造函数注入依赖项不是一个好选择。所以我尝试了...
[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);
...
}
}
...但是属性注入似乎在这里不起作用。该服务已在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();
}
< p >Autofac是否支持IAsyncAuthorizationFilter
类型的自动装配?如果不支持,我该如何实现该功能?
[TypeFilter(typeof(CustomAuthenticationAttribute))]
在控制器上注册你的过滤器吗?你可以在这里获取更多信息:https://joonasw.net/view/aspnet-core-di-deep-dive - juunas