Search code examples
c#asp.net-corekestrel

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


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.


Solution

  • 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;
    

    .NET 6 or higher

    Starting from .NET 6 using the new application bootstrapping model you can access the environment from the application builder:

    var builder = WebApplication.CreateBuilder(args);
    var isDevelopment = builder.Environment.IsDevelopment();