在控制器之外获取当前用户

Get current User outside of Controller

在 ASP.NET Core 2.2 控制器上,我有以下内容:

var principal = this.User as ClaimsPrincipal;

var authenticated = this.User.Identity.IsAuthenticated;

var claims = this.User.Identities.FirstOrDefault().Claims;

var id = this.User.FindFirstValue(ClaimTypes.NameIdentifier);

我能够检查用户是否是 authenticated 并获取 claims 包括 id

如何在没有 this.UserController 之外做同样的事情?

IHttpContextAccessor接口注入目标class。这将允许通过 HttpContext

访问当前 User

这提供了一个机会,通过创建一个服务来提供您想要的信息(即当前登录的用户)来抽象此功能

public interface IUserService {
    ClaimsPrincipal GetUser();
}

public class UserService : IUserService {
    private readonly IHttpContextAccessor accessor;

    public UserService(IHttpContextAccessor accessor) {
        this.accessor = accessor;
    }

    public ClaimsPrincipal GetUser() {
        return accessor?.HttpContext?.User as ClaimsPrincipal;
    }
}

您现在需要在 Startup.ConfigureServices 中设置 IHttpContextAccessor 以便能够注入它:

services.AddHttpContextAccessor();
services.AddTransient<IUserService, UserService>();

并在需要的地方注入您的服务。

It's important to note that HttpContext could be null. Just because you have IHttpContextAccessor, doesn't mean that you're going to actually be able to always get the HttpContext. Importantly, the code where you're using this must be within the request pipeline in some way or HttpContext will be null.

来自评论@ChrisPratt