由于缺少合适的构造函数,aspnet core 2.1动作过滤器出现错误 [英] Getting error with aspnet core 2.1 action filter due to missing suitable constructor

查看:57
本文介绍了由于缺少合适的构造函数,aspnet core 2.1动作过滤器出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个索赔过滤器

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:适合' Foosball.Logic.ClaimRequirementFilter'类型的构造函数.找不到.确保类型是具体的,并为公共构造函数的所有参数注册服务

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/足球

推荐答案

您的代码具有

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

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

you need to add the following constructor:

public ClaimRequirementFilter(Claim claim)
{

}

这是因为内部构造函数解析逻辑使用 TypeFilterAttribute.Argument 属性来确定要用于实例化的构造函数.

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

这篇关于由于缺少合适的构造函数,aspnet core 2.1动作过滤器出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆