做了角色注解。但是 Claim 注释如何呢?

Did the Role annotation. But how is Claim annotation?

我正在学习一个正在教我如何使用角色和声明的教程。首先,它教我们如何使用角色,除此之外,我不得不在 ApplicationUserManager.cs 代码中添加以下行:

    public const string Administrator = "Admin";

由于该项目的想法是一个 IMDB 页面,只有管理员可以在其中创建新的电影流派,所以我不得不添加注释

    [Authorize(Roles = ApplicationUserManager.Administrator)] /* role annotation */
    [HttpPost]
    [Route("Api/Genres")]
    public async Task<IHttpActionResult> PostAsync(GenrePostRequest request)
    {
        using (var db = new ApplicationDbContext())
        {
            await Genre.CreateAsync(request.Name, GetUserId(), db, Request.GetOwinContext().GetUserManager<ApplicationUserManager>());
            return Ok();
        }
    }

GenreController.cs 上的 Post 函数之前,如上所示。一切正常。一切都是好的。现在,教程说要在 ApplicationUserManager.cs 代码中添加这两行:

    public const string IsAdminClaim = "IsAdmin";
    public const string IsAdminClaimValue = "True";

所以我可以使用声明。

教程现在说“更新 GenreController 的创建操作以使用通过指定声明创建的注释。

我知道 GenreController 的创建操作在哪里,但是声明的注释应该是什么样子的?

我知道我有一个叫 AuthorizationAttribute.cs 的 class,它看起来有点像:

public class AuthorizationAttribute : AuthorizationFilterAttribute
{
    public string ClaimType { get; set; }
    public string ClaimValue { get; set; }

    public AuthorizationAttribute(string claimType, object claimValue)
    {
        this.ClaimType = claimType;
        this.ClaimValue = claimValue.ToString();
    }
    public override Task OnAuthorizationAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
    {
        /* some codes */
    }
}

已解决! 我正在尝试使用 Authorize 作为 Role 的不同变体,但是作为构建声明的 class 具有如下构造函数:

public AuthorizationAttribute(string claimType, object claimValue)
{
    this.ClaimType = claimType;
    this.ClaimValue = claimValue.ToString();
}

如问题所示,正确的注释是:

[Authorization(ApplicationUserManager.IsAdminClaim, ApplicationUserManager.IsAdminClaimValue)]

也就是说,使用 Authorization,而不是 Authorize