.net core get user in ValidationAttribute

核能气质少年 提交于 2019-12-06 09:12:47
Kirk Larkin

ValidationContext has its own GetService method, which is preconfigured to use the ASP.NET Core Dependency Injection container (the IServiceProvider) when resolving services. Here's an example of how it would work in your situation:

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

        ...
    }
}

In order to get to HttpContext, you can use IHttpContextAccessor, which is resolved here using GetService as described above (you'll need to make sure you've registered it with DI, using e.g. AddHttpContextAccessor).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!