在 Program.Main 中访问 ASP.NET 内核中的环境名称

使用 ASP.NET Mvc Core 我需要将我的开发环境设置为使用 https,所以我在 Program.cs 中的 Main方法中添加了以下内容:

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();

如何访问这里的宿主环境,以便有条件地设置协议/端口号/证书?

理想情况下,我会使用 CLI 来操纵我的托管环境,如下所示:

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

但似乎没有办法使用来自命令行的证书。

56353 次浏览

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();

[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();
}

In .NET core 3.0

using System;
using Microsoft.Extensions.Hosting;

then

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