如何從ApplicationDbContext.OnConfiguring獲取HTTP上下文?

asp.net-core entity-framework-core httpcontext

我通過查詢數據庫中的數據來驗證中間件中的HTTP請求,為此我需要使用HTTP請求中的數據配置ApplicationDbContext。如何從ApplicationDbContext.OnConfiguring到達HTTP請求? (ASP .NET核心/實體框架核心)

中間件

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中註入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
       ...
   }

並且不要忘記將IHttpContextAccessor註冊到ConfigureServices中的DI作為“ 默認情況下未註冊IHttpContextAccessor服務

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


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow