.Net5:如何从 Program.cs 获取环境名称
.Net5: How do I get the EnvironmentName from Program.cs
以下代码在 Net Core 3.1 中运行良好,但在 .Net 5 中不起作用
var webHostBuilder = WebHostBuilder(args);
var environment = webHostBuilder.GetSetting("environment");
使用 GetService
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
var hostBuilder = CreateHostBuilder(args).Build();
var hostEnvironment = hostBuilder.Services.GetService<IHostEnvironment>();
// Get EnvironmentName
var environment = hostEnvironment?.EnvironmentName; // Possible values: Development, Production, CustomEnvironment, etc..
hostBuilder.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
以下代码在 Net Core 3.1 中运行良好,但在 .Net 5 中不起作用
var webHostBuilder = WebHostBuilder(args);
var environment = webHostBuilder.GetSetting("environment");
使用 GetService
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
var hostBuilder = CreateHostBuilder(args).Build();
var hostEnvironment = hostBuilder.Services.GetService<IHostEnvironment>();
// Get EnvironmentName
var environment = hostEnvironment?.EnvironmentName; // Possible values: Development, Production, CustomEnvironment, etc..
hostBuilder.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}