在控制器外获取当前用户 [英] Get current User outside of Controller

查看:76
本文介绍了在控制器外获取当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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并获取包括idclaims.

I am able to check if the user is authenticated and gets the claims including id.

在没有this.UserController之外,我该如何做?

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

这篇关于在控制器外获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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