如何从 ApplicationDbContext.OnConfiguring 获取 HTTP 上下文?

How to get HTTP context from ApplicationDbContext.OnConfiguring?

我通过查询数据库中的数据来验证中间件中的 HTTP 请求,为此我需要使用 HTTP 请求中的数据配置 ApplicationDbContext。如何从 ApplicationDbContext.OnConfiguring 到达 HTTP 请求? (ASP .NET 核心/Entity framework 核心)

中间件

public class TeamAuthentication
{
    public async Task Invoke(HttpContext context, ApplicationDbContext db)
    {
        My.CheckToken(db);
        // ...

DbContext

public class ApplicationDbContext :  IdentityDbContext<ApplicationUser>
{
    private ILoggerFactory loggerFactory;

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, ILoggerFactory _loggerFactory)
        : base(options)
    {
        loggerFactory = _loggerFactory;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // how to reach HttpContext here ?
        // ...

如您所知,EF 支持将 DbContext 与依赖项注入容器一起使用。在您的依赖项中注入 IHttpContextAccessor 并使用它来获取当前的 HttpContext:

public class ApplicationDbContext :  IdentityDbContext<ApplicationUser>
{
   private readonly ILoggerFactory _loggerFactory;
   private readonly IHttpContextAccessor _contextAccessor;

   public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, ILoggerFactory loggerFactory, IHttpContextAccessor contextAccessor)
    : base(options)
   {
       _loggerFactory = loggerFactory;
       _contextAccessor = contextAccessor;
   }

   protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
   {
       // use _contextAccessor.HttpContext here
       ...
   }

并且不要忘记在 ConfigureServices 中将 IHttpContextAccessor 注册到 DI 为“The IHttpContextAccessor service is not registered by default

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
    ...
}