Search code examples
asp.netasp.net-coreasp.net-core-mvckestrel-http-serverkestrel

Determining Hosting Environment While Configuring Kestrel and UseHttps


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

Update

I raised the following GitHub issue.


Solution

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