Asp.Net 核心 ActionFilter - 如何传递不同数量的参数

fro*_*sty 4 c# asp.net-core asp.net-core-2.0

我想将不同数量的参数传递给 ActionFilter。例子:

[TypeFilter(typeof(AuthorizeFilter), Arguments = new object[] {PolicyName.CanUpdateModule, PolicyName.CanReadModule })]
public async Task<IActionResult> PutModule([FromRoute] Guid id, [FromBody] Module module)
Run Code Online (Sandbox Code Playgroud)

我定义了如下过滤器,我收到错误“InvalidOperationException:找不到适合类型‘MyApp.AuthFilters.AuthorizeFilter’的构造函数。确保类型是具体的,并且服务已为公共构造函数的所有参数注册。”。我该如何解决这个问题?

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();
    }...
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*rco 6

关闭但没有雪茄。您正在使用错误的参数调用过滤器。您已经将其称为 a 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*/
}
Run Code Online (Sandbox Code Playgroud)

尽管如此,您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;
    }
    /* ... */
}
Run Code Online (Sandbox Code Playgroud)