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

时间:2017-01-10 08:28:17

标签: 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 ?
        // ...

1 个答案:

答案 0 :(得分:2)

正如您已经发现的,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
       ...
   }

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

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