Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set the port for Net.Core application in launchSettings.JSON

I've edited launchSettings.JSON file and changed the port like so.

"Gdb.Blopp": {
  "commandName": "Project",
  "launchBrowser": false,
  "launchUrl": "http://localhost:4000",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development"
  }

It still starts on port 5000, though. Is that setting disregarded all toghether or am I missing something else?

like image 651
Konrad Viltersten Avatar asked Dec 18 '22 12:12

Konrad Viltersten


2 Answers

The launchSettings.json supposed to be used by IDEs (i.e. Visual Studio), when you hit F5/Ctr+F5 and offers the options from the pull-down menu next to the start button.

enter image description here

Also you shouldn't directly edit that the launcherSettings.json file and instead use the Project Properties to change stuff.

One reason for this is that if you change it via project properties, Visual Studio will also edit the IIS Express files (located in the .vs/config/applicationhost.config folder of your solution).

If you want to change the port kestrel uses, use .UseUrls("http://0.0.0.0:4000") (get it either from appsettings.json or hosting.json) in Program.cs.

If you don't want to use hardcoded, you can also do something like this

Create a hosting.json:

{
  "server": "Microsoft.AspNetCore.Server.Kestrel",
  "server.urls": "http://localhost:4000"
}

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        var config = new ConfigurationBuilder()
            .AddJsonFile("hosting.json", optional: false)
            .AddEnvironmentVariables(prefix: "ASPNETCORE_")
            .Build();

        var host = new WebHostBuilder()
            .UseConfiguration(config)
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

You can also do that via commandline (AddCommandLine call is important here, from Microsoft.Extensions.Configuration.CommandLine" package).

var config = new ConfigurationBuilder()
    .AddCommandLine(args)
    .Build();

var host = new WebHostBuilder()
    .UseConfiguration(config)
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();

host.Run();

Then run it via dotnet run server.urls=http://0.0.0.0:4000.

When you run IIS/IISExpress the kestrel port will be determined by UseIISIntegration().

like image 69
Tseng Avatar answered May 04 '23 01:05

Tseng


Since .NET Core 2.0 you don't have to maintain hosting.json or modify app startup anymore. There is built-in support for setting app port, explained here: https://stackoverflow.com/a/49000939/606007

like image 41
Random Avatar answered May 04 '23 01:05

Random