ASP.NET Core 在自定义 AuthorizeAttribute 中传递 int 属性

问题描述 投票:0回答:1

我正在尝试创建一个自定义

AuthorizeAttribute
来添加我的功能。这是我遵循的步骤

我创建了

MyCustomAttribute
类:

public class MyCustomAttribute : AuthorizeAttribute
{
    public MyCustomAttribute ()
    {
        Policy = "CustomAttribute";
    }
}

我创建了处理程序类:

public class MyCustomAttributeHandler : IAuthorizationHandler
{
    public async Task HandleAsync(AuthorizationHandlerContext context)
    {
        //Some logic
        return;
    }
}

我在

program.cs
中注册了属性,如下所示:

builder.Services.AddScoped<IAuthorizationHandler, MyCustomAttributeHandler >();

我在函数上方添加了属性

[CustomAttribute]
public async Task<DTO> AddAsync(DTO dTO)
{
     //some logic
}

到目前为止,它运行完美,但我还需要 1 个步骤。

我需要将一个整数传递给

[CustomAttribute]
以便在处理程序中读取它。

我怎样才能实现这个目标?

c# asp.net-core asp.net-core-mvc asp.net-core-webapi
1个回答
0
投票

您可以修改属性类以包含可以保存要传递的整数值的属性。下面是例子:

首先修改MyCustomAttribute类以接受int参数并保存:

public class MyCustomAttribute : AuthorizeAttribute, IAuthorizationRequirement
{
    public int MyCustomValue { get; }

    public MyCustomAttribute(int customValue)
    {
        Policy = "CustomAttribute";
        MyCustomValue = customValue;
    }
}

提取int值的MyCustomAttributeHandler类代码:

public class MyCustomAttributeHandler : AuthorizationHandler<MyCustomAttribute>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyCustomAttribute requirement)
    {
        int customValue = requirement.MyCustomValue;
        
        if (customValue == /* condition */)
        {
            context.Succeed(requirement);
        }
        
        return Task.CompletedTask;
    }
}

注册处理程序:

builder.Services.AddSingleton<IAuthorizationHandler, MyCustomAttributeHandler>();

将自定义属性与方法上方的整数参数一起使用:

[MyCustomAttribute(42)] 
public async Task<DTO> AddAsync(DTO dTO)
{
    .....
    .......
}
© www.soinside.com 2019 - 2024. All rights reserved.