且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Net Core 在 DbContext 中获取用户信息

更新时间:2023-02-12 21:50:26

我实施了一种类似的方法,该方法在 这篇博文 主要涉及创建一个服务,该服务将使用依赖注入来注入 HttpContext(和潜在的用户信息)到特定的上下文中,或者您更喜欢使用它.

I implemented an approach similar to this that is covered in this blog post and basically involves creating a service that will use dependency injection to inject the HttpContext (and underlying user information) into a particular context, or however you would prefer to use it.

一个非常基本的实现可能看起来像这样:

A very basic implementation might look something like this:

public class UserResolverService  
{
    private readonly IHttpContextAccessor _context;
    public UserResolverService(IHttpContextAccessor context)
    {
        _context = context;
    }

    public string GetUser()
    {
       return _context.HttpContext.User?.Identity?.Name;
    }
}

您只需要在 Startup.cs 文件中的 ConfigureServices 方法中将其注入管道:

You would just need to inject this into the pipeline within the ConfigureServices method in your Startup.cs file :

services.AddTransient<UserResolverService>();

最后,只需在您指定的 DbContext 的构造函数中访问它:

And then finally, just access it within the constructor of your specified DbContext :

public partial class ExampleContext : IExampleContext
{
    private YourContext _context;
    private string _user;
    public ExampleContext(YourContext context, UserResolverService userService)
    {
        _context = context;
        _user = userService.GetUser();
    }
}

然后您应该能够使用 _user 在您的上下文中引用当前用户.这也可以轻松扩展为存储/访问当前请求中可用的任何内容.

Then you should be able to use _user to reference the current user within your context. This can easily be extended to store / access any content available within the current request as well.