Configure ASP.NET Core 2.0 Kestrel for HTTPS

好久不见. 提交于 2019-11-27 19:27:10
poke

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);
            });
        }
    }
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!