steve
steve

Reputation: 927

Publishing to IIS uses wrong appSettings.json

I have a .NET Core 2.1 web API i am hosting locally with IIS. I have two child appSettings.json files, Development and Production. I have also created these environments within my project. My publishing profile uses Debug profile. When I actually debug my code it works perfectly fine.

The issue I have is that when I publish to IIS under a private IP and access it, it seems my code using the wrong appSettings.json file. I know this because I have different file paths used for different environments and it prints out the one from Production.

Even weirder when I physically delete appSettings.Production.json from my inetput/wwwroot/{MyProject} folder, then Postman cannot even talk to the API and I get a 500 bad request. Maybe I am not configuring or linking correctly? This is my first time working with environments.

I have lost about 4 hours on this and I am losing it...

Program.cs

public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(ConfigConfiguration)
                .UseStartup<Startup>();

        static void ConfigConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder config)
        {
            config.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appSettings.{ctx.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);

        }

Any more info required, do let me know!

Upvotes: 2

Views: 3923

Answers (2)

AaBa
AaBa

Reputation: 471

For publishing the code on local IIS using a specific development app settings i.e. Dev1 or Dev2 etc, add the below line manually in FolderProfile.pubxml and then publish.

<PropertyGroup>
  <EnvironmentName>Dev1 OR Dev2 OR ..</EnvironmentName>
</PropertyGroup>

Once publish is completed, an element will be added in Web.Config to make use of the appropriate app setting file at runtime.

<environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Dev1 OR Dev2 OR .." />
</environmentVariables>

Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-6.0#windows---iis-deployments

Upvotes: 0

user7217806
user7217806

Reputation: 2119

Ensure to set the ASPNETCORE_ENVIRONMENT environment variable on the server, see Use multiple environments in ASP.NET Core .

Upvotes: 1

Related Questions