Search code examples
c#dockervisual-studioasp.net-coreaspnetcore-environment

Why setting env variables for ports such as ASPNETCORE_HTTP_PORT doesn't work in Visual Studio


I have such a startup profile for my project in launcSettings.json.

"http": {
  "commandName": "Project",
  "launchBrowser": true,
  "launchUrl": "swagger",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development",
    "ASPNETCORE_HTTP_PORTS": "8087",
    "ASPNETCORE_HTTPS_PORTS": "8088"
  }

But the application opens on port 5000. Why is this happening? When starting in docker-compose and specifying these environment variables, the application opens on the correct ports.


Solution

  • It seems that Visual Studio forcibly sets ASPNETCORE_URLS when starting the application - see this question:

    "ASPNETCORE_URLS": "https://localhost:5001;http://localhost:5000"
    

    when applicationUrl and ASPNETCORE_URLS are not specified in the start profile (which is your case).

    This interferes with setting the ports separately:

    "ASPNETCORE_HTTP_PORTS": "8087",
    "ASPNETCORE_HTTPS_PORTS": "8088"
    

    When I run from Visual Studio 2022 under .NET 8 with your configuration I get:

    warn: Microsoft.AspNetCore.Hosting.Diagnostics[15]
          Overriding HTTP_PORTS '8087' and HTTPS_PORTS '8088'. Binding to values defined by URLS instead 'https://localhost:5001/;http://localhost:5000/'.
    info: Microsoft.Hosting.Lifetime[14]
          Now listening on: https://localhost:5001
    info: Microsoft.Hosting.Lifetime[14]
          Now listening on: http://localhost:5000
    

    This doesn't happen when you use the same profile (e.g. named Dev) from the command line (or supply the env variables via Docker as your initial test)

    dotnet run --launch-profile Dev
    

    Output:

    info: Microsoft.Hosting.Lifetime[14]
          Now listening on: http://[::]:8087
    info: Microsoft.Hosting.Lifetime[14]
          Now listening on: https://[::]:8088
    info: Microsoft.Hosting.Lifetime[0]
          Application started. Press Ctrl+C to shut down.
    

    So the issue is Visual Studio. I am not sure how to turn off this behavior with a program setting, but the workaround I found answering the other question is to set ASPNETCORE_URLS to empty in launchSettings.json:

    "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Development",
      "ASPNETCORE_URLS": "",
      "ASPNETCORE_HTTP_PORTS": "8087",
      "ASPNETCORE_HTTPS_PORTS": "8088"
    }
    

    I've tested this and it works for your case too on Visual Studio 2022 17.12 (.NET 8/ASP.NET 8)