ASP. NET Core Kestrel using HTTPS (SSL)

  • 2021-08-16 23:36:19
  • OfStack

In ASP. NET Core, if you want to use HTTPS in Kestrel for encrypted transport of the site, you can do the following

Apply for a certificate

This step will not be detailed, there are free and charged, after the application will give you a *. pfx ending file.

Add an NuGet package

nuget and then add references to the program Microsoft. AspNetCore. Server. Kestrel. Https

Configure

Copy the *. pfx ending file to the program's Web root directory, and then modify the Programs. cs file:


  public class Program
 {
  public static void Main(string[] args) {
   var config = new ConfigurationBuilder().AddCommandLine(args).AddEnvironmentVariables("ASPNETCORE_").Build();

   var host =
    new WebHostBuilder().UseConfiguration(config).UseKestrel(ConfigHttps()).UseContentRoot(
     Directory.GetCurrentDirectory()).UseIISIntegration().UseStartup<Startup>().Build();
   
   host.Run();
  }

  private static Action<KestrelServerOptions> ConfigHttps() {
   return x => {
    var pfxFile = Path.Combine(Directory.GetCurrentDirectory(), "*.pfx");
    //password  Fill in the key of the application 
    var certificate = new X509Certificate2(pfxFile, "password");
    x.UseHttps(certificate);
   };
  }
 } 

Then the command line window runs dotnet xxx. dll-server. urls https://www. example. com: port.


Related articles: