如何在ASP.NET Core 2.x中使用Kestrel的HTTPS / SSL?

rwqw0loc  于 5个月前  发布在  .NET
关注(0)|答案(2)|浏览(88)

我目前使用的是ASP.NET Core 2.x,我过去可以让Kestrel使用HTTPS / SSL,只需将其放入UseUrls()方法中,如下所示:

var host = new WebHostBuilder()
    .UseUrls("http://localhost", "https://111.111.111.111")
    .UseKestrel()
    .Build();

字符串
但现在我得到了一个例外:

System.InvalidOperationException:
     HTTPS endpoints can only be configured using KestrelServerOptions.Listen().

如何在ASP.NET Core 2.x中配置Kestrel以使用SSL?

xfyts7mz

xfyts7mz1#

基础知识。使用服务器URL

如果您想关联您的服务器以使用分配给服务器/Web主机的所有IP地址,那么您可以这样做:

WebHost.CreateDefaultBuilder(args)
    .UseUrls("http://localhost:5000", "http://*:80")
    .UseStartup<Startup>()
    .Build();

字符串

  • 注意:UseUrls()方法中使用的字符串格式为:http://{ip address}:{port number}
  • 如果您使用*(krsks)作为IP地址,则意味着主机上的所有可用IP地址。
  • 端口号不是必需的。如果您将其留空,则默认为端口80。*
  • 这里有关于UseUrls()方法的大量其他细节,请参阅Microsoft官方文档。*

但是,SSL将不与UseUrls()方法一起工作--因此,这意味着如果您尝试添加以https://开头的URL,程序将抛出异常

System.InvalidOperationException:
    HTTPS endpoints can only be configured using KestrelServerOptions.Listen().

端点配置,使用HTTPS并绑定SSL证书

HTTPS端点只能使用KestrelServerOptions配置。
下面是使用Listen方法使用TCP套接字的示例:

WebHost.CreateDefaultBuilder(args)
    .UseKestrel(options =>
    {
        options.Listen(IPAddress.Loopback, 5000);  // http:localhost:5000
        options.Listen(IPAddress.Any, 80);         // http:*:80
        options.Listen(IPAddress.Loopback, 443, listenOptions =>
        {
            listenOptions.UseHttps("certificate.pfx", "password");
        });
    })
    .UseStartup<Startup>()
    .Build();


注意:如果同时使用Listen方法和UseUrlsListen端点将覆盖UseUrls端点。

  • 您可以在Microsoft官方网站上找到有关设置端点的更多信息。*

如果使用IIS,IIS的URL绑定将覆盖通过调用ListenUseUrls设置的任何绑定。有关详细信息,请参阅Introduction to ASP.NET Core Module

mu0hgdu0

mu0hgdu02#

你不需要单独用kestrel实现https。如果你运行的应用程序需要https,它很可能会面向互联网。这意味着你需要在nginx或Apache后面运行kestrel,并让其中一个为你处理https请求。

相关问题