.net core 在 ValidationAttribute 中获取用户

.net core get user in ValidationAttribute

我正在尝试在自定义 ValidationAttribute 中访问当前用户(即来自身份的 ClaimsPrincipal),但我还没有弄清楚如何才能做到这一点。

public class UniqueTitleValidator : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
      // var user = ?
    }
}

我知道我可以从 HttpContext 访问用户(但我不知道如何访问后者)。

主要问题是我无权访问用户。当我在 属性 上使用自定义 ValidatorAttribute 时,当构建 属性 时,用户(或 HttpContext)为空。意思是我不能,例如将 User 交给 Validator 的构造函数。这就是为什么我想知道如何让验证器了解用户的一些信息(and/or 它的声明)。如果我可以访问任何一个,例如验证器中的 HttpContext 或 User,我也可以获得所有其他运行时信息。我的问题可以理解吗?

ValidationContext has its own GetService method, which is preconfigured to use the ASP.NET Core Dependency Injection container, IServiceProvider,解析服务时。这是一个例子:

public class UniqueTitleValidator : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var httpContextAccessor = (IHttpContextAccessor)validationContext.GetService(typeof(IHttpContextAccessor));
        var user = httpContextAccessor.HttpContext.User;

        ...
    }
}

要到达 HttpContext,请使用 IHttpContextAccessor, which is resolved here using GetService as described above. You'll need to make sure you've registered this with DI, using e.g. AddHttpContextAccessor