在下面的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 issue。
答案 0 :(得分:2)
事实证明,您可以使用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();
}
}
答案 1 :(得分:0)
我已经尝试过了,它似乎确实有效,但你可能不会再仔细检查......
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();
}
}