Home > Net >  .net core application can't find the correct appsettings using environment variables
.net core application can't find the correct appsettings using environment variables

Time:10-15

I have a simple .net core application. It's using WebApplicationBuilder to create the instance of the application at runtime.

The code in the program.cs looks like this:

    var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .Enrich.FromLogContext()
    .CreateLogger();

builder.WebHost.ConfigureLogging(logging =>
{
    logging.ClearProviders();
    logging.AddConsole();
    logging.AddSerilog(logger);
});

My launchsetting.json looks like this:

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:29881",
      "sslPort": 44344
    }
  },
  "profiles": {
    "MyApp.Api": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:7134;http://localhost:5134",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

When running this app using the MyApp.Api profile locally, it works. It uses appsetting.Development.json and transforms it's json values over appsetting.json.

However, when I publish and deploy the application to a server outside of my local environment, it doesn't use the provided appsetting.CURRENT.json.

The environment variables are set as follow:

Environment=ASPNETCORE_ENVIRONMENT=CURRENT
Environment=DOTNET_ENVIRONMENT=CURRENT

And I can see the files being deployed to the correct directory.

-rw-r--r--  1 root root    2397 Oct 13  2022 appsettings.CURRENT.json
-rw-r--r--  1 root root    1527 Oct 13  2022 appsettings.json

I'm completely out of ideas. Any help is deeply appreciated.

CodePudding user response:

I think you're looking to use CreateDefaultBuilder.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host?view=aspnetcore-6.0

That one will use appsettings.{Environment}.json automatically (more detail on what it does at that link.

CodePudding user response:

I suggest a different approach:

if(builder.Environment.IsProduction())
{
  builder.Configuration.AddJsonFile(
    "appsettings.CURRENT.json",
    optional: false, reloadOnChange: true
  );
}

https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.jsonconfigurationextensions

  • Related