Search code examples
c#configurationasp.net-core-webapiappsettings.net-7.0

How can I prevent appsettings.json values from being overridden when running on localhost in .NET 7 Web API?


I want the configuration values from appsettings.json to remain unchanged when running on localhost. I have already added separate appsettings.{env}.json files to other environments. I want to use appsettings.Development.json file only for Dev environment not for localhost.

Do i need to create separate appsettings.Localhost.json file? Or Can I create new profile (Localhost) like below? Please suggest.

"Localhost": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7055;http://localhost:5065",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Localhost"
      }
    }

Below is my Program.cs

var builder = WebApplication.CreateBuilder(args);
{
    // Environment configuration
    var configuration = builder.Configuration;

    var env = builder.Environment;

    configuration
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);


    builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Program>());
    builder.Services.AddHttpClient();

    builder.Services.AddApplication();
    builder.Services.AddInfrastructure(builder.Configuration);

    builder.Services.AddHelpers();

    builder.Services.AddControllers()
       // Configures the JSON serialization options for controllers.
       .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
        });

    builder.Services.Configure<ApiBehaviorOptions>(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });

} 

Solution

  • I have a test in my side, I add a configuration in appsettings.json. When I changed the launch settings to Localhost, then it would read variable in appsettings.Localhost.json

    enter image description here

    enter image description here