Home > Net >  Change connection string according the domain at runtime
Change connection string according the domain at runtime

Time:05-27

to write an api I need to change the value of the string connection according to the domain. is this possible in startup.cs?

CodePudding user response:

In your program.cs(.Net 6), Choose the specified ConnectionStrings by domain name or other what you want, Then you can configure like this:

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;
        }
});

CodePudding user response:

Xinran's answer is true.

As an alternative, you can use this approach that has worked for me in production environment (in .NET 5).

At first add these lines to ConfigureServices method in Startup.cs:

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

And then in your data context file, you must modify Constructor and OnConfiguring methods.

Constructor method:

private readonly HttpContext _httpContext;

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

In appsetting.json, you can set connection strings and then modify the OnConfiguring method:

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.Host.Host.ToString();
        if (host == "domain1"))
                {
            connection = configuration.GetConnectionString("Connection1");
        }
        if (host == "domain2"))
                {
            connection = configuration.GetConnectionString("Connection2");
        }
        optionsBuilder.UseSqlServer(connection);
    }
} 

   
  • Related