在控制器外获取当前用户 [英] Get current User outside of Controller
问题描述
在ASP.NET Core 2.2控制器上,我具有以下内容:
On an ASP.NET Core 2.2 controller I have the following:
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
并获取包括id
的claims
.
I am able to check if the user is authenticated
and gets the claims
including id
.
在没有this.User
的Controller
之外,我该如何做?
How can I do the same outside of the Controller
where I do not have this.User
?
推荐答案
将IHttpContextAccessor
接口注入目标类.这将允许通过HttpContext
Inject IHttpContextAccessor
interface into the target class. This will give access to the current User
via the HttpContext
这通过创建仅提供所需信息的服务(这是当前登录用户)提供了抽象此功能的机会
This provides an opportunity to abstract this feature by creating a service to provide just the information you want (Which is the current logged in 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
才能注入它:
You need to setup IHttpContextAccessor
now in Startup.ConfigureServices
in order to be able to inject it:
services.AddHttpContextAccessor();
services.AddTransient<IUserService, UserService>();
并在需要的地方注入您的服务.
and inject your service where needed.
请务必注意,
HttpContext
可能为 null .只是因为 您有IHttpContextAccessor
,并不意味着您要 实际上总是能够得到HttpContext
.重要的是,代码在哪里 您正在以某种方式在请求管道中使用此必须或HttpContext
将为 null .
It's important to note that
HttpContext
could be null. Just because you haveIHttpContextAccessor
, doesn't mean that you're going to actually be able to always get theHttpContext
. Importantly, the code where you're using this must be within the request pipeline in some way orHttpContext
will be null.
通过评论信用 @ChrisPratt
这篇关于在控制器外获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!