Configure ASP.NET Core 2.0 Kestrel for HTTPS

前端 未结 1 430
青春惊慌失措
青春惊慌失措 2020-12-08 08:06

TL;DR What is today the correct way to setup HTTPS with ASP.NET Core 2.0?

I would like to configure my project to use https and a certificate like they have shown at

相关标签:
1条回答
  • 2020-12-08 08:45

    Unfortunately, the way of configuration-based way of setting up HTTPS that has been shown in various videos or tutorials before the launch of ASP.NET Core 2.0 didn’t make it into the final release.

    For 2.0, the only way to configure HTTPS is in code, by explicitly setting up the Kestrel listeners, as explained in this announcement, and using ListenOptions.UseHttps to enable HTTPS:

    var host = new WebHostBuilder()
        .UseKestrel(options =>
        {
            options.ListenAnyIP(443, listenOptions => 
            {
                listenOptions.UseHttps("server.pfx", "password");
            });
        })
        .UseStartup<Startup>()
        .Build();
    

    Unfortunately, at the time of release, the official documentation also did not cover this properly and advertised the configuration-based way that wasn’t implemented. This has been fixed since.

    Starting with ASP.NET Core 2.1, configuration based HTTPS setup will be possible, as originally promised. This will likely look like this, as explained by Tratcher on GitHub:

    "Kestrel": {
      "Endpoints": {
        "HTTPS": {
          "Url": "https://*:443",
          "Certificate": {
            "Path": "server.pfx",
            "Password": "password"
          }
        }
      }
    }
    

    In your particular example, the code-based configuration would look like the following. Note that if you don’t want to use a certificate file, you need to manually retrieve the certificate from the certificate store first.

    .UseKestrel(options =>
    {
        // listen for HTTP
        options.ListenLocalhost(40000);
    
        // retrieve certificate from store
        using (var store = new X509Store(StoreName.My))
        {
            store.Open(OpenFlags.ReadOnly);
            var certs = store.Certificates.Find(X509FindType.FindBySubjectName, 
                "localhost", false);
            if (certs.Count > 0)
            {
                var certificate = certs[0];
    
                // listen for HTTPS
                options.ListenLocalhost(40001, listenOptions =>
                {
                    listenOptions.UseHttps(certificate);
                });
            }
        }
    })
    
    0 讨论(0)
提交回复
热议问题