Search code examples
c#self-hosting.net-core-3.0

Self-hosted Net Core 3 application does not take port settings


I feel silly asking this as there are dozens of articles on Net Core hosting, but I have tried everything and I am still having the issue.

I am attempting to change the port used by a self-hosted web service. I have altered the launchSettings.json file.

"MyService": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_URLS": "http://*:51248",
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:51248"
    },
    "MyService": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_URLS": "http://*:51248",
        "ASPNETCORE_ENVIRONMENT": "Release"
      },
      "applicationUrl": "http://localhost:51248"
    }

I have also attempted to set the port through direct configuration:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<MyServiceWorker>();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseUrls("http://*:51248");
                    webBuilder.UseStartup<Startup>();
                })
                .ConfigureWebHost(config => { config.UseUrls("http://*:51248"); })
                .UseWindowsService()
                .UseSerilog();
    }

Everything works fine if I run through Visual Studio, but if I run the executable directly, it still uses port 5000. If I run it as a Windows service, it seems to pick some random port.

I have hit dozens of web sites, but have not found a solution. Does anyone have any suggestions?


Solution

  • I feel pretty foolish, but I will post this in case it helps someone else. What I have discovered is that .UseUrls does work if the application is run as a Windows service. The launchSettings.json settings work when launching from within Visual Studio. I have not been able to change the listening port when just running as a console application.

    It turns out that the problem was an artifact of the way that I was testing the application. Hopefully no one else will waste a lot of time doing the same thing.