gpt4 book ai didi

c# - 在 Controller 之外获取当前用户

转载 作者:行者123 更新时间:2023-12-03 19:44:14 24 4
gpt4 key购买 nike

在 ASP.NET Core 2.2 Controller 上,我有以下内容:

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 .

我怎样才能在 Controller 之外做同样的事情?我没有的地方 this.User ?

最佳答案

注入(inject) IHttpContextAccessor接口(interface)到目标类。这将允许访问当前的 User通过 HttpContext
这提供了一个通过创建一个服务来提供你想要的信息来抽象这个特性的机会(这是当前登录的用户)

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;
}
}

您需要设置 IHttpContextAccessor现在在 Startup.ConfigureServices为了能够注入(inject)它:
services.AddHttpContextAccessor();
services.AddTransient<IUserService, UserService>();

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

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通过评论

关于c# - 在 Controller 之外获取当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57990635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com