How to use HTTPS / SSL with Kestrel in ASP.NET Cor

2019-01-21 13:30发布

问题:

I am currently using ASP.NET Core 2.x and I used to be able to get Kestrel to to use HTTPS / SSL by simply putting it in the UseUrls() method like so:

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

But now I get the exception:

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

How do I configure Kestrel to use SSL in ASP.NET Core 2.x?

回答1:

The basics. Using Server URLs

If you want to associate your server to use all the IP addresses assigned to the server/web host then you can do this:

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

Note: The string format used in the UseUrls() method is: http://{ip address}:{port number}.
- If you use an * (asterisks) for the IP address, that means all available IP address on the host.
- The port number is not a requirement. If you leave it blank it will default to port 80.

There is a great amount of additional detail about the UseUrls() method over at the official Microsoft Docs here.

However, SSL will not work with the UseUrls() method --- so, that means if you try to add a URL starting with https:// the program will throw the exception

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

Endpoint configuration. Using HTTPS and binding a SSL certificate

HTTPS endpoints can only be configured using KestrelServerOptions.

Here is an example of using TCP sockets using the Listen method:

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

Note: That if you use both the Listen method and UseUrls, the Listen endpoints override the UseUrls endpoints.

You can find more info about setting up endpoints here at the official Microsoft Docs.

If you use IIS, the URL bindings for IIS override any bindings that you set by calling either Listen or UseUrls. For more information, see Introduction to ASP.NET Core Module.



回答2:

You don't need to implement https with kestrel by itself. If you are running an application that requires https, it is most likely going to face outward to the internet. This means you need to run kestrel behind nginx or Apache and have one of those handle the https request for you.