代码之家  ›  专栏  ›  技术社区  ›  Mech0z

由于缺少合适的构造函数,aspnet core 2.1操作筛选器出现错误

  •  0
  • Mech0z  · 技术社区  · 6 年前

    我做了一个索赔过滤器

    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”类型的构造函数。思维方式找不到ClaimRequirementFilter“”。确保类型是具体的,并且为公共构造函数的所有参数注册了服务

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Set    6 年前

    就像你的代码一样

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

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

    public ClaimRequirementFilter(Claim claim)
    {
    
    }
    

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