Getting error with aspnet core 2.1 action filter due to missing suitable constructor

◇◆丶佛笑我妖孽 提交于 2021-02-11 13:37:35

问题


I have made a claims filter

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();
        }
    }

}

I have registered the filter in my startup

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

        services.AddScoped<ClaimRequirementFilter>();

But I get this error when I navigate to an action that uses the filter

[HttpPost]
[ClaimRequirement("Permission", ClaimRoles.Admin)]
public async Task ResetLeaderboard()

InvalidOperationException: A suitable constructor for type 'Foosball.Logic.ClaimRequirementFilter' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor

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


回答1:


As your code has

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

you need to add the following constructor:

public ClaimRequirementFilter(Claim claim)
{

}

That is because the internal constructor resolving logic uses TypeFilterAttribute.Argument property to decide what constructor to use for instantiation.



来源:https://stackoverflow.com/questions/50377449/getting-error-with-aspnet-core-2-1-action-filter-due-to-missing-suitable-constru

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!