Search code examples
asp.net-core.net-coreasp.net-core-2.2kestrel

How to use domain url with kestrel in Asp.Net core app?


I have a project with asp.net core 2.2 in windows os.

I deploy the project and run with kesterl with this command:

dotnet myapp.dll

that's run in http://localhost:5000.

I need to run the website in mydomain.com.

I set mydomain.com in hosts for 127.0.0.1 ip.

how to set this configuration?


Solution

  • When you run an ASP.NET Core application directly through Kestrel, without an additional reverse proxy like IIS or nginx, you will need to configure the hosting URL properly. There are a few options that are described in detail in the endpoint configuration chapter of the documentation:

    By default, ASP.NET Core binds to:

    Specify URLs using the:

    • ASPNETCORE_URLS environment variable.
    • --urls command-line argument.
    • urls host configuration key.
    • UseUrls extension method.

    A very common solution for this is to change the environment variable. This allows you to set the URL in a very flexible way which is very useful for quickly launching the application. When you start the server from the command line, this could look like this:

    # PowerShell
    PS> $env:ASPNETCORE_URLS = 'http://example.com'
    PS> dotnet myapp.dll
    
    # cmd
    > set ASPNETCORE_URLS=http://example.com
    > dotnet myapp.dll
    
    # bash
    $ ASPNETCORE_URLS=http://example.com dotnet myapp.dll
    

    A more permanent (but still flexible) solution would be to specify the Kestrel configuration as part of the appsettings.json file. This also allows you to configure a HTTPS certificate if you want to host over HTTPS.

    This could for example look like this:

    {
      "Kestrel": {
        "Endpoints": {
          "Http": {
            "Url": "http://example.com"
          },
          "Https": {
            "Url": "https://example.com",
            "Certificate": {
              "Path": "<path to .pfx file>",
              "Password": "<certificate password>"
            }
          }
        }
      }
    }
    

    For more details, check the documentation on hosting with Kestrel.

    If you want to host the application on a common port, you should remember that there can only ever be a single process that listens on a port. So if you have some other application already listening on port 80 and 443, you will not be able to host your application with Kestrel on those ports. This is a limitation of the hosting model with just Kestrel since every application is a separate process. In contrast, hosting through a reverse proxy, such as IIS or nginx, allows you to to host multiple applications on the same port because it is the reverse proxy process that is listening on those ports.