当在主入口点使用WebHostBuilder时,我如何指定它绑定到的端口?

默认情况下,它使用5000。

请注意,这个问题是特定于新的ASP。NET Core API(目前在1.0.0-RC2中)。


当前回答

后续的回答将帮助任何人在VS docker集成中做到这一点。我需要更改到端口8080以使用谷歌appengine中的“灵活”环境运行。

你需要在Dockerfile中添加以下内容:

ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080

您需要在docker-compose中修改端口。Yml也是:

    ports:
      - "8080"

其他回答

您可以指定托管URL,而不需要对应用程序进行任何更改。

创建Properties/launchSettings。Json文件,然后像这样填充它:

{
  "profiles": {
    "MyApp1-Dev": {
        "commandName": "Project",
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        },
        "applicationUrl": "http://localhost:5001/"
    }
  }
}

dotnet运行命令应该选择您的启动设置。Json文件,并将其显示在控制台中:

C:\ProjectPath [master ≡]
λ  dotnet run
Using launch settings from C:\ProjectPath\Properties\launchSettings.json...
Hosting environment: Development
Content root path: C:\ProjectPath
Now listening on: http://localhost:5001
Application started. Press Ctrl+C to shut down. 

详情:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments

或者,你也可以通过命令行运行app来指定端口。

简单地运行命令:

dotnet run --server.urls http://localhost:5001

注意:其中5001是要运行的端口。

我用以下方法修复了Net core 3.1中的端口问题

在Program.cs中

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
        .ConfigureWebHost(x => x.UseUrls("https://localhost:4000", "http://localhost:4001"))
        .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}

您可以使用

http://localhost:4000

https://localhost:4001

如果使用dotnet运行

dotnet run --urls="http://localhost:5001"

后续的回答将帮助任何人在VS docker集成中做到这一点。我需要更改到端口8080以使用谷歌appengine中的“灵活”环境运行。

你需要在Dockerfile中添加以下内容:

ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080

您需要在docker-compose中修改端口。Yml也是:

    ports:
      - "8080"