0

I have my website hosted in the mywebsite folder of www.example.com and I visit https://www.example.com/mywebsite/home/about.

I have a requirement to get the domain name from baseurl and based on the domain name we need to change the config connectionstring

How do I get the base url part in program.cs? The part that I am looking for is https://www.example.com

BalMahad
  • 1
  • 2
  • Why do you want to get "domain name" in the `Program.cs`? It's impossible. Can you explain more? – Will Huang Dec 04 '21 at 11:25
  • We want to implement multi tenancy architecture in our project. For each new client there will be a new database. We are storing the connection string in the parameter store in AWS. we are getting the config values from the parameter store in program.cs. so we want the domain name in the program.cs so based on the domain name we will fetch the connection string from parameter store. – BalMahad Dec 04 '21 at 12:58
  • I think this answer might fit your needs: https://stackoverflow.com/a/43078074/910074 – Will Huang Dec 04 '21 at 13:30
  • Thanks for the link. we are taking the config values from the aws parameter store like this in our program.cs. "host.ConfigureAppConfiguration(builder => builder.AddSystemsManager($"{env}"));". So i have to get the all the config values of the new client from program.cs itself. if i get the domain name in program.cs i thought of adding the domain name next to env $"{env}/domainname" so i can get the config values of that client.Please advise. – BalMahad Dec 06 '21 at 05:34
  • @Will Huang I am able to get the domain using the below code. var host1 = BuildWebHost(null); host1.Start(); var serverAddress = host1.ServerFeatures.Get(); private static IWebHost BuildWebHost(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseStartup() .Build(); }.As my project is .net core 3.1 now GenericHost is the new standard. Can we use both WebHost and GenericHost in the same project? – BalMahad Dec 07 '21 at 12:55
  • There is no use case for use both WebHost and GenericHost. You might need to think another way to solve your problem. – Will Huang Mar 13 '22 at 16:31

1 Answers1

3
public class HomeController : Controller
{
private readonly ILogger<homecontroller> _logger;
private readonly IHttpContextAccessor _httpContextAccessor;
public HomeController(ILogger<homecontroller> logger, IHttpContextAccessor httpContextAccessor)
{
_logger = logger;
_httpContextAccessor = httpContextAccessor;
}
}

Once the above setup is done, the host name can be accessed in any action using the below line of code:

string host = _httpContextAccessor.HttpContext.Request.Host.Value;
A.M
  • 119
  • 4