Reza
Reza

Reputation: 13

Change connection string according the domain at runtime

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

Upvotes: 1

Views: 742

Answers (2)

Ali
Ali

Reputation: 26

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

   

Upvotes: 1

Xinran Shen
Xinran Shen

Reputation: 9963

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

Upvotes: 1

Related Questions