在下面的 ASP.NET Core Main 方法中,如何确定托管环境,以便我可以在 HTTPS 的不同证书文件之间切换?
public sealed class Program
{
public static void Main(string[] args)
{
new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseKestrel(
options =>
{
if ([Development Hosting Environment])
{
options.UseHttps("DevelopmentCertificate.pfx");
}
else
{
options.UseHttps("ProductionCertificate.pfx");
}
})
.UseIISIntegration()
.UseStartup<Startup>()
.Build()
.Run();
}
}
更新
我提出了以下 GitHub 问题。
事实证明,
您可以使用ConfigureServices
来获取IHostingEnvironment
,如下所示:
public sealed class Program
{
public static void Main(string[] args)
{
IHostingEnvironment hostingEnvironment = null;
new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureServices(
services =>
{
hostingEnvironment = services
.Where(x => x.ServiceType == typeof(IHostingEnvironment))
.Select(x => (IHostingEnvironment)x.ImplementationInstance)
.First();
})
.UseKestrel(
options =>
{
if (hostingEnvironment.IsDevelopment())
{
// Use a self-signed certificate to enable 'dotnet run' to work in development.
options.UseHttps("DevelopmentCertificate.pfx", "password");
}
})
.UseIISIntegration()
.UseStartup<Startup>()
.Build()
.Run();
}
}
我已经尝试过这个,它似乎确实有效,但你可能不想仔细检查......
public class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddEnvironmentVariables()
.Build();
var pfx = config["ASPNETCORE_ENVIRONMENT"].Equals("Development", StringComparison.CurrentCultureIgnoreCase)
? "DevelopmentCertificate.pfx"
: "ProductionCertificate.pfx";
var host = new WebHostBuilder()
.UseKestrel(options =>
{
options.UseHttps(pfx);
})
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}