由于缺少合适的构造函数而导致aspnet core 2.1动作过滤器出错

时间:2018-05-16 18:07:51

标签: c# asp.net-web-api asp.net-core .net-core

我制作了声明过滤器

public class ClaimRequirementAttribute : TypeFilterAttribute
{
    public ClaimRequirementAttribute(string claimType, ClaimRoles claimValue) : base(typeof(ClaimRequirementFilter))
    {
        Arguments = new object[] {new Claim(claimType, claimValue.ToString()) };
    }
}

public class ClaimRequirementFilter : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var headers = context.HttpContext.Request.Headers;

        var tokenSuccess = headers.TryGetValue("Token", out var token);

        var emailSuccess = headers.TryGetValue("Email", out var email);

        var deviceNameSuccess = headers.TryGetValue("DeviceName", out var deviceName);

        if (tokenSuccess && emailSuccess && deviceNameSuccess)
        {
            var accountLogic = context.HttpContext.RequestServices.GetService<IAccountLogic>();

            var hasClaim = accountLogic.ValidateLogin(email, token, deviceName).Result.Success;

            if (!hasClaim)
            {
                context.HttpContext.ForbidAsync();
            }
        }
        else
        {
            context.HttpContext.ForbidAsync();
        }
    }

}

我已在我的启动中注册了过滤器

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<ConnectionStringsSettings>(Configuration.GetSection("ConnectionStrings"));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        services.AddScoped<ClaimRequirementFilter>();

但是当我导航到使用过滤器的操作

时,我收到此错误
[HttpPost]
[ClaimRequirement("Permission", ClaimRoles.Admin)]
public async Task ResetLeaderboard()
  

InvalidOperationException:无法找到类型为“Foosball.Logic.ClaimRequirementFilter”的合适构造函数。确保类型具体,并为公共构造函数的所有参数注册服务

github:https://github.com/Mech0z/Foosball/tree/core2.1/Foosball

1 个答案:

答案 0 :(得分:1)

正如您的代码

Arguments = new object[] {new Claim(claimType, claimValue.ToString()) };

您需要添加以下构造函数:

public ClaimRequirementFilter(Claim claim)
{

}

这是因为internal constructor resolving logic使用TypeFilterAttribute.Argument属性来决定用于实例化的构造函数。