1

In my ASPNET Core App, how to overload / overwrite appsettings based on current url ?

I have actually one application "my app", in .NET 6. I host this application in IIS, 2 times :

http://local.domain1.com/myapp

http://local.domain2.com/myapp

"myapp" is publish on C:\publish\app\myapp with it's own appsettings.json

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var env = builder.Environment;
builder.Configuration
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
    .AddEnvironmentVariables();

I want to add an another json file based on actual url :

if (HttpContext.Request.Host.Host == "local.domain1.com")
{
    // Load appsettings in C:\publish\shared\domain1\appsettings.json
}
else if (HttpContext.Request.Host.Host == "local.domain2.com")
{
    // Load appsettings in C:\publish\shared\domain2\appsettings.json
}

But in Program.cs, i don't have access to HttpContext. If I create a custom middlware, i can't call builder.Configuration.AddJsonFile(...)

How to do ?

Thank you

Pika
  • 11
  • 2
  • Are those two applications in physically different directories? – Dusan Mar 11 '22 at 13:42
  • Nope. 1 app, 1 publish time, 1 physical directory C:\publish\app\myapp – Pika Mar 11 '22 at 13:44
  • You should not overwrite the settings files even if they were separate... You just need to load appropriate ones... – Dusan Mar 11 '22 at 13:52
  • Maybe create 2 IIS applications pointing to the same directory and put different environment variable value for each... Then, in the code, based on this variable value, load different settings files. https://stackoverflow.com/a/36836533/461810 – Dusan Mar 11 '22 at 13:53
  • When i host an aspnet core on IIS, it's create a web.config with environment variables. But, myapp it's publish only 1 time on my disk. So http://local.domain1... and http://local.domain2... use the same web.config and the same environment variable :(. I use IIS 8. – Pika Mar 11 '22 at 14:04
  • As I said... you can register **TWO** applications under IIS that point to the same directory. Those two would execute independently of each other, in separate processes. The you can configure different environment variables for each of them, and those variables are not stored in `web.config` but in the IIS global `applicationHost.config`. https://stackoverflow.com/a/37455594/461810 – Dusan Mar 11 '22 at 16:46
  • Other solution would be to tie your settings to the request as you have asked. But that requires a lot of adjustments in the application, and might be even impossible in some cases (if consumer does not allow you to inject the at runtime during the request) – Dusan Mar 11 '22 at 16:53
  • 1
    I use inheritance of web.config ans it works ! Thank you Dusan – Pika Mar 12 '22 at 10:08

0 Answers0