在运行时根据域更改连接字符串

Change connection string according the domain at runtime

写一个api我需要根据域更改字符串连接的值。 这在 startup.cs 中可能吗?

在你的program.cs(.Net 6)中,通过域名或者其他你想要的方式选择指定的ConnectionStrings,然后你可以这样配置:

builder.Services.AddHttpContextAccessor();


builder.Services.AddDbContext<AppDataContext>();


builder.Services.AddScoped(sp =>
{ 
        var httpContext = sp.GetService<IHttpContextAccessor>().HttpContext;
        var DomainName = httpContext.Request.Host.Value;
          var builder = new DbContextOptionsBuilder<AppDataContext>();
        if (DomainName == "hostname1")
        {
            builder.UseSqlServer("connectstring-hostname1");
            return builder.Options;
        }
        else if (DomainName == "hostname2")
        {
            builder.UseSqlServer("connectstring-hostname2");
            return builder.Options;
        }
        else
        {
            builder.UseSqlServer("connectstring-else");
            return builder.Options;
        }
});

欣然的回答是正确的。

作为替代方案,您可以使用在生产环境(在 .NET 5 中)对我有用的这种方法。

首先将这些行添加到 Startup.cs 中的 ConfigureServices 方法:

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddDbContext<your data context>();

然后在您的数据上下文文件中,您必须修改 Constructor 和 OnConfiguring 方法。

构造方法:

private readonly HttpContext _httpContext;

public YourDBContext(DbContextOptions<YourDBContext> options, IHttpContextAccessor httpContextAccessor = null)
            : base(options)
{
      _httpContext = httpContextAccessor?.HttpContext;
}

在appsetting.json中可以设置连接字符串,然后修改 OnConfiguring 方法:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        //default connection
        var connection = configuration.GetConnectionString("Connection");
        var host = _httpContext.Request.Headers["Referer"].ToString();
        if (host == "domain1"))
                {
            connection = configuration.GetConnectionString("Connection1");
        }
        if (host == "domain2"))
                {
            connection = configuration.GetConnectionString("Connection2");
        }
        optionsBuilder.UseSqlServer(connection);
    }
}