Access environment name in Program.Main in ASP.NET Core
Asked Answered
S

5

123

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.

Synapse answered 8/6, 2017 at 13:39 Comment(0)
F
236

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();
Fourscore answered 8/6, 2017 at 13:58 Comment(4)
Note that in .NET Core 3.0+, the EnvironmentName class is marked as obsolete (learn.microsoft.com/en-us/dotnet/api/…), with the recommendation you switch to the Environments class (learn.microsoft.com/en-us/dotnet/api/…).Caloric
This only works when environment is set by the environment variable. It's also possible to set it from the command line with --environment "Development" for exampleRecitation
How would you do this if you're not using asp.net at all? Like if it's just a console app?Shrunken
Been searching the internet for this for an hour or so now and just found this simple solution! Thanks so much! I needed this for EF method override of OnConfiguring(DbContextOptionsBuilder optionsBuilder)Microgamete
G
35

[New Answer using ASP 6.0 minimal API]:

If you are using ASP 6.0 minimal API it's very simple by using WebApplication.Environment:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

if (!app.Environment.IsProduction())
{
    // ...
}

app.MapGet("/", () => "Hello World!");

app.Run();

======================================

[Old Answer]

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();
}
Gramnegative answered 5/7, 2018 at 16:1 Comment(6)
The problem with this is it creates an entire instance of the application and destroys it again just to get the Environment name. Very heavy handed.Filariasis
@steed given that this is a clean way to get the IHostingEnvironment and it is only done once before Run() I would say it's neglectable if it's a bit "heavy handed".Lemkul
Need access to it before web host builder Build is caleldNaturalism
@Filariasis util you don't call Run, as in CreateHostBuilder(args).Build().Run(), you aren't really creating the entire instance of the application, you just created the host, and requested an instance of IHostingEnvironmentAunt
IHostingEnvironment has been deprecated and can be replaced with Microsoft.AspNetCore.Hosting.IWebHostEnvironment or Microsoft.Extensions.Hosting.IHostEnvironmentDisapprobation
Not sure about previous versions, but in .NET7, as soon as I call CreateBuilder, I seem to have access to builder.Environment.EnvironmentName. This is before ever calling builder.Build().Themis
A
13

In .NET core 3.0

using System;
using Microsoft.Extensions.Hosting;

then

var isDevelopment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == Environments.Development;
Acupuncture answered 8/7, 2020 at 4:5 Comment(0)
C
0

Most answers here use some form of built-in function to determine whether or not the environment is development or not. .NET Core has 3 built-in environment names: Development, Staging and Production.

However, it's possible to specify other names as well. For example, you may have a "QA" environment and want to use that name. Or you may have more than just the three environments.

That's why I think a better approach is to inject the IWebHostEnvironment instance (if possible) and IWebHostEnvironment.EnvironmentName instead.

Croton answered 19/2 at 13:37 Comment(0)
C
0

In .Net 8 program.cs just call:

builder.Environment.EnvironmentName
Chanson answered 9/4 at 12:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.