0
votes

I use this same method to set the eonvironmentname for a web app that I publish to a folder. However, when publishing a .net core console app that is using IWebhostBuilder, the environmentname isnt seeming to get updated?

I have a .net core console app that I am publishing to a folder location and the console app uses IWebhostBuilder, hence I need to be able to set the environment name prior to publishing. It seems to want to grab the default appsettings, rather than the one for my target environment (Dev). I have a appsettings.Dev.json file

enter image description here

My publish profile looks like this

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <PublishProtocol>FileSystem</PublishProtocol>
    <Configuration>Dev</Configuration>
    <Platform>Any CPU</Platform>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <PublishDir>\\dev-server1\d$\Services\BoxService</PublishDir>
    <SelfContained>false</SelfContained>
    <_IsPortable>true</_IsPortable>
    <EnvironmentName>Dev</EnvironmentName>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>
  </PropertyGroup>
</Project>

[ Edit ]
Nothing was working, so I did an experiment because obviously I am missing something or just dont understand. I created a new test console app with nothing in it except one class with a Main method. Added the necessary packages (Extensions.Configuration etc), then proceeded to publish the app to a local folder with the following in my publishprofile.

<EnvironmentName>Local</EnvironmentName>

This is obviously not being used, because when I run it from visual studio, it reports the correct environment has been set, but when run from the published folder, its as if the environment has not been set.

Here is Program.cs 
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.EnvironmentVariables;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Cmd1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");


            var environmentName =
                Environment.GetEnvironmentVariable("ENVIRONMENT");

            // create service collection
            var services = new ServiceCollection();


            // build config
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", false)
                .AddJsonFile($"appsettings.{environmentName}.json", true)
                .AddEnvironmentVariables()
                .Build();

            // setup config
            services.AddOptions();
            services.Configure<AppSettings>(configuration.GetSection("App"));

            // create service provider
            var serviceProvider = services.BuildServiceProvider();

            var appSettings = serviceProvider.GetService<IOptions<AppSettings>>();

            string env = Environment.GetEnvironmentVariable("Environment");

            Console.WriteLine($" We are looking at {appSettings.Value.TempDirectory} from environment: {env}");
        }
    }
}

Appsettings.json

{
  "App": {
    "TempDirectory": "d:\temp"
  }
}

Appsettings.Local.json

{
  "App": {
    "TempDirectory": "c:\\temp\\rss-hero\\tmp\\"
  }
}

Setting Environment in VS enter image description here

Results, from VS

enter image description here

Results when run from published folder enter image description here

1
After the publish open Powershell in publish dir. Run $Env:ENVIRONMENT = "Development" and then start the application using dotnet .\appName.dll. Your application will use the specified env you specified earlier in the command.Muhammad Hannan

1 Answers

-1
votes

You need to configure IWebhostBuilder like this

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .ConfigureAppConfiguration(builder =>
    {
        builder.AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.Dev.json", optional: true) // add more if you have
            .AddEnvironmentVariables();
    });

Then depending on the environment it will use appsettings{envrionment}.json. If no other present it will use appsettings.json (default). After publishing you can check the web.config to check the environment name it's using.

EDIT

For console app you do something like this

private static IConfigurationBuilder Configure(IConfigurationBuilder config, string environmentName)
    {
        return config
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();
    }

And use like this (.Net core generic host)

Host.CreateDefaultBuilder(args)
.ConfigureHostConfiguration(builder =>
{
    Configure(builder, "Dev");
})
.UseConsoleLifetime()

Or if you want to get the environment from System environment variables.

public static IConfiguration CreateConfiguration()
    {
        var env = new HostingEnvironment
        {
            EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"),
            ApplicationName = AppDomain.CurrentDomain.FriendlyName,
            ContentRootPath = AppDomain.CurrentDomain.BaseDirectory,
            ContentRootFileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory)
        };

        var config = new ConfigurationBuilder();
        var configured = Configure(config, env);
        return configured.Build();
    }