I'd like to pass varying number of parameters to an ActionFilter. example:
[TypeFilter(typeof(AuthorizeFilter), Arguments = new object[] {PolicyName.CanUpdateModule, PolicyName.CanReadModule })]
public async Task<IActionResult> PutModule([FromRoute] Guid id, [FromBody] Module module)
I defined filter like below and I get the error "InvalidOperationException: A suitable constructor for type 'MyApp.AuthFilters.AuthorizeFilter' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.". How do I get around this issue?
public class AuthorizeFilter : ActionFilterAttribute
{
private readonly IAuthorizationService _authService;
private readonly string[] _policyNames;
public AuthorizeFilter(IAuthorizationService authService,params string[] policyNames)
{
_authService = authService;
_policyNames = policyNames.Select(f => f.ToString()).ToArray();
}...
}
答案 0 :(得分:3)
关闭但没有雪茄。您使用错误的参数调用过滤器。您已将其称为TypeFilterAttribute
,因为您需要传入DI 和参数。
现在你只需修复你的论点。你想传入一个字符串数组,但你传入了几个字符串。
[TypeFilter(typeof(AuthorizeFilter),
Arguments = new object[] {
new string[] { PolicyName.CanUpdateModule, PolicyName.CanReadModule }
}
)]
public async Task<IActionResult> PutModule([FromRoute] Guid id, [FromBody] Module module) {
/*do stuff*/
}
尽管如此,您的IAuthorizationService
仍然需要在DI容器中注册才能得到解决。
然后,您需要从params
课程中删除AuthorizeFilter
关键字:
public class AuthorizeFilter : ActionFilterAttribute
{
private readonly IAuthorizationService _authService;
private readonly string[] _policyNames;
public AuthorizeFilter(IAuthorizationService authService,string[] policyNames)
{
_authService = authService;
_policyNames = policyNames;
}
/* ... */
}