In the ASP.NET Core Main method below, how can I determine the hosting environment, so I can switch between different certificate files for 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();
}
}
I raised the following GitHub issue .
It turns out you can use ConfigureServices
to get hold of IHostingEnvironment
like so:
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();
}
}
I've tried this and it did seem to work, but you might wan't to double check...
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.