【问题标题】:HttpContext is null when creating ApplicationDbContext创建 ApplicationDbContext 时 HttpContext 为空
【发布时间】:2020-04-03 14:57:32
【问题描述】:

我正在尝试在我的 Core 3.1 MVC 应用程序中实现多租户。我看到如下示例,但是当我运行我的应用程序时,HttpContext 为空,我不明白为什么。唯一的区别是我使用 ApplicationDbContext 但据我了解,它无论如何都是从 DbContext 继承的......

public class PlaylistContext : DbContext
{
    private int _tenantId;
    private string _tenantHost;

    public DbSet<Playlist> Playlists { get; set; }
    public DbSet<Song> Songs { get; set; }

    public PlaylistContext(DbContextOptions<PlaylistContext> options,
                           IHttpContextAccessor accessor)
        : base(options)
    {
        _tenantHost = accessor.HttpContext.Request.Host.Value;
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        var connection = Database.GetDbConnection();
        using (var command = connection.CreateCommand())
        {
            connection.Open();

            command.CommandText = "select ID from Tenants where Host=@Host";
            command.CommandType = CommandType.Text;

            var param = command.CreateParameter();
            param.ParameterName = "@Host";
            param.Value = _tenantHost;

            command.Parameters.Add(param);
            _tenantId = (int)command.ExecuteScalar();
            connection.Close();
        }

        foreach (var type in GetEntityTypes())
        {
            var method = SetGlobalQueryMethod.MakeGenericMethod(type);
            method.Invoke(this, new object[] { modelBuilder });
        }

        base.OnModelCreating(modelBuilder);
    }

    // Other methods follow
}

我的代码

public ApplicationDbContext(
            DbContextOptions<ApplicationDbContext> options,
            IHttpContextAccessor http,
            ILogger<ApplicationDbContext> logger,
            ITenantService tenantService
            )
            : base(options)
        {
            _http = http; // <-- _http.HttpContext is null
            _logger = logger;
            _tenantService = tenantService;
        }

我的服务

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options => {
                options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
                options.EnableSensitiveDataLogging(true);
            });

            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddControllersWithViews()
            .AddRazorRuntimeCompilation()
            .AddNewtonsoftJson(options=>{
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

            services.AddRazorPages();

            services.AddMultiTenancy()
                .WithResolutionStrategy<HostResolutionStrategy>()
                .WithStore<TenantStore>();

            services.AddScoped<ITenantService, TenantService>();

        }

【问题讨论】:

  • 能否请您出示一下您从 startup.cs 注册的服务?
  • 当然。我添加了我的服务注册。
  • 我创建了一个新的 MVC 应用程序并将 IHttpContextAccessor 注入到 ApplicationDbContest 中,它的 HttpContext 不为空......这令人困惑。
  • 您是否尝试过services.AddHttpContextAccessor(),如答案所示?
  • 是的,我没有任何变化。 IHttpContextAccessor 是由框架提供的

标签: .net-core dependency-injection


【解决方案1】:

尝试将此行添加到服务注册中:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

services.AddHttpContextAccessor();

此链接显示访问HttpContext 的方法:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-3.1

【讨论】:

    【解决方案2】:

    请注意,即使对于新上下文,OnModelCreating 也会被调用一次。 这也将在 HttpRequest 之外执行,这就是 HttpContext 为空的原因。

    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      • 2023-03-17
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多