How to use HTTPS / SSL with Kestrel in ASP.NET Core 2.x?

Solution 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.