Access environment name in Program.Main in ASP.NET Core

C#asp.net CoreKestrel

C# Problem Overview


Using ASP.NET Mvc Core I needed to set my development environment to use https, so I added the below to the Main method in Program.cs:

var host = new WebHostBuilder()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseKestrel(cfg => cfg.UseHttps("ssl-dev.pfx", "Password"))
                .UseUrls("https://localhost:5000")
                .UseApplicationInsights()
                .Build();
                host.Run();

How can I access the hosting environment here so that I can conditionally set the protocol/port number/certificate?

Ideally, I would just use the CLI to manipulate my hosting environment like so:

dotnet run --server.urls https://localhost:5000 --cert ssl-dev.pfx password

but there doesn't seem to be way to use a certificate from the command line.

C# Solutions


Solution 1 - C#

I think the easiest solution is to read the value from the ASPNETCORE_ENVIRONMENT environment variable and compare it with Environments.Development:

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var isDevelopment = environment == Environments.Development;

Solution 2 - C#

This is my solution (written for ASP.NET Core 2.1):

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        var hostingEnvironment = services.GetService<IHostingEnvironment>();
        
        if (!hostingEnvironment.IsProduction())
           SeedData.Initialize();
    }

    host.Run();
}

Solution 3 - C#

In .NET core 3.0

using System;
using Microsoft.Extensions.Hosting;

then

var isDevelopment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == Environments.Development;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike LunnView Question on Stackoverflow
Solution 1 - C#Henk MollemaView Answer on Stackoverflow
Solution 2 - C#HamedHView Answer on Stackoverflow
Solution 3 - C#Moses MachuaView Answer on Stackoverflow