.net核心在ValidationAttribute中获取用户 [英] .net core get user in ValidationAttribute

查看:116
本文介绍了.net核心在ValidationAttribute中获取用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过自定义的ValidationAttribute访问当前用户(即,身份中的ClaimsPrincipal),但我还不知道该怎么做。

I am trying to access the current user (i.e. ClaimsPrincipal from identity) in a custom ValidationAttribute, and I haven't figured out how I could do that.

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

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

I know that I could access the user from a HttpContext (but I don't know how to get to the latter).

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

The main problem is that I don't have access to the User. When I use a custom ValidatorAttribute on a property, when the property gets constructed the User (or also HttpContext) is null. Meaning that I can't e.g. give the User to the Validator's constructor. That's why I'm wondering how the Validator could be made to know something about the User (and/or its claims). If I can access any of e.g. HttpContext or User inside the validator, I can get to all the other runtime information as well. Is my question understandable?

推荐答案

ValidationContext 有其自己的 GetService 方法,该方法已预先配置为使用ASP.NET Core依赖注入容器 IServiceProvider 。下面是一个示例:

ValidationContext has its own GetService method, which is preconfigured to use the ASP.NET Core Dependency Injection container, IServiceProvider, when resolving services. Here's an example:

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 ,此处使用 GetService 如上所述。您需要确保已使用例如 AddHttpContextAccessor

To get to HttpContext, use 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.

这篇关于.net核心在ValidationAttribute中获取用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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