ChatGPT解决这个技术问题 Extra ChatGPT

如何指定托管 ASP.NET Core 应用程序的端口?

Main 入口点中使用 WebHostBuilder 时,如何指定它绑定到的端口?

默认情况下,它使用 5000。

请注意,此问题特定于新的 ASP.NET Core API(当前在 1.0.0-RC2 中)。

检查 Properties 文件夹中的 launchSettings.json。您可以在 launchUrl 中更改端口。
@Oleg,我在 RC1 的项目模板中留下了一些与 IIS 相关的设置。他们没有任何效果。
可以使用 hosting.json(参见 the answer),这是 RC1 中默认使用的,只需添加 .AddJsonFile("hosting.json", optional: true)(参见 here
使用配置堆栈似乎确实比依赖纯粹的 VS 特定机制(launchSettings.json)好得多。
@DrewNoakes:我在 my old answer 中附加了 UPDATED 2 部分。它描述了更改默认端口和使用 hosting.json 或用于配置绑定的命令行的一些变体。

K
Kévin Chalet

在 ASP.NET Core 3.1 中,有 4 种主要方法可以指定自定义端口:

使用命令行参数,通过使用 --urls=[url] 启动您的 .NET 应用程序:

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

使用 appsettings.json,通过添加 Urls 节点:

{
  "Urls": "http://localhost:5001"
}

使用环境变量,ASPNETCORE_URLS=http://localhost:5001/。

使用 UseUrls(),如果您更喜欢以编程方式执行此操作:

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(builder =>
            {
                builder.UseStartup<Startup>();
                builder.UseUrls("http://localhost:5001/");
            });
}

或者,如果您仍在使用 Web 主机构建器而不是通用主机构建器:

public class Program
{
    public static void Main(string[] args) =>
        new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://localhost:5001/")
            .Build()
            .Run();
}

在我看来,直接在代码中使用固定 URL 并不是最佳选择。
对此进行了测试,效果很好,谢谢。 @Oleg,您能否详细说明您需要什么配置的答案?将它放在配置文件中可能会很好。
@Oleg 也许,但使用 UseUrls 是 ASP.NET 团队推荐的用于自托管方案的方法(显然,值本身不必硬编码)。也就是说,我更新了我的答案,提到了如何使用配置生成器来做到这一点。
@Pinpoint:我发布了 the old answer,其中可以找到如何使用 hosting.json 更改端口。唯一需要做的就是强制读取 RC2 中的信息(参见 the announcement)。
您需要以下软件包:using Microsoft.Extensions.Configuration.CommandLine;
m
menxin

您可以在 asp.net core 2.1+ appsettings.json 文件中插入 Kestrel 部分。

  "Kestrel": {
    "EndPoints": {
      "Http": {
        "Url": "http://0.0.0.0:5002"
      }
    }
  },

如果你没有红隼部分,你可以使用“urls”:

{
    "urls":"http://*.6001;https://*.6002"
}

但如果您在 appsettings.json 中有红隼,则 urls 部分将失败。


谢谢,正是我所需要的 :-) 比 UseUrls() 更好。更多详情:docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/…
这实际上适用于通过 dotnet publish 生成的二进制文件。
这不是定义 the port Kestrel is binded to IIS (proxy) 而不是应用程序在 IIS 中托管的端口吗?
@user12345 在 IIS 托管中,Kestrel 使用动态端口绑定。
也适用于从 exe 运行 web api 的 netcore 3.0,太棒了!!!
C
Casey

跟进答案以帮助任何使用 VS docker 集成执行此操作的人。我需要更改为端口 8080 才能使用 google appengine 中的“灵活”环境运行。

您的 Dockerfile 中需要以下内容:

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

您还需要修改 docker-compose.yml 中的端口:

    ports:
      - "8080"

谢谢,我们可以用同样的方式在 windows 命令提示符中设置变量:set ASPNETCORE_URLS=http://*:8080
这对我不起作用。你确定这就是你修改的全部吗?您是否需要对图像后记或 docker 做任何特别的事情?
时间太长了,它可能已经改变了,但如果我记得这就是我需要做的一切。
在 VS Code 中,您可以在 launch.json 的“env”部分添加“ASPNETCORE_URLS”:“http://+:8080”,以覆盖其他设置。
D
Drew Noakes

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

在您的项目目录中创建一个 Properties/launchSettings.json 文件,并用以下内容填充它:

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

dotnet run 命令应选择您的 launchSettings.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://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments


也在 appSettings.json 中工作?
不,它必须在 [ProjectRoot]/Properties/launchSettings.json 中,但美妙的是,它可以顺利运行。
这仅在开发期间有用,不适用于二进制文件。要使用 dotnet run,您需要访问源代码。
T
TetraDev

替代解决方案是在项目的根目录中使用 hosting.json

{
  "urls": "http://localhost:60000"
}

然后在 Program.cs

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", true)
        .Build();

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

    host.Run();
}

这对我不起作用。 server.urls 现在是 urls 并确保将条目添加到 project.json "publishOptions": { "include": [ "appsettings.json", "web.config", "wwwroot", "hosting.json" ] },
我用正确的属性 urls 更新了他的答案 - 谢谢@ManishJain
j
jabu.hlong

如果使用 dotnet run

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

完美答案!在码头工作。仅将“localhost”替换为“0.0.0.0”
o
oudi

以上 .net core 2.2 方法 Main 支持 args 和 WebHost.CreateDefaultBuilder(args)

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

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

您可以构建您的项目并像这样转到 bin 运行命令

dotnet <yours>.dll --urls=http://0.0.0.0:5001

或使用多个网址

dotnet <yours>.dll --urls="http://0.0.0.0:5001;https://0.0.0.0:5002"

编辑 2021/09/14

在 .net core 3.1 之后,您可以更改项目中的文件 appsettings.json,Config 部分 UrlsKestrel 都可以正常工作。你可以使用任何一个。 Urls 会更容易。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "MicrosoftHostingLifetime": "Information"
    }
  },
  "Urls": "http://0.0.0.0:5002",
  //"Kestrel": {
  //  "EndPoints": {
  //    "Http": {
  //      "Url": "http://0.0.0.0:5000"
  //    },
  //    "Https": {
  //      "Url": "https://0.0.0.0:5001"
  //    }
  //  }
  //},
  "AllowedHosts": "*"
}

使用 http://0.0.0.0:5000 可以从远程连接访问网络服务器,如果您设置为 http://localhost:5000 则只能在您的计算机中访问。

要使 Kestrel 设置生效,您应该在项目中更改 Program.cs 中的代码。

        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureServices((context, services) =>
                 {
                     services.Configure<Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions>(context.Configuration.GetSection("Kestrel"));
                 });
                webBuilder.UseStartup<Startup>();
            });

您可以在项目目录中简单地使用 'dotnet run --urls=0.0.0.0:5001'
这个答案对我有用。对于多 URL 的情况,我必须将逗号 , 更改为分号,如下所示:--urls="http://localhost:5001;https://localhost:5002"。否则,启动 Kestrel 时出错:System.InvalidOperationException: A path base can only be configured using IApplicationBuilder.UsePathBase().
R
R. van Diesen

当托管在 docker 容器(我的 Linux 版本)中时,您可能会收到“连接被拒绝”消息。在这种情况下,您可以使用 IP 地址 0.0.0.0 ,这意味着“这台机器上的所有 IP 地址”而不是 localhost 环回来修复端口转发。

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://0.0.0.0:5000/")
            .Build();

        host.Run();
    }
}

B
Burak Kalafat

在 .Net Core 3.1 上,只需遵循 Microsoft Doc 即可,它非常简单:kestrel-aspnetcore-3.1

总结一下:

将以下 ConfigureServices 部分添加到 Program.cs 上的 CreateDefaultBuilder: // 使用 Microsoft.Extensions.DependencyInjection;公共静态 IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.Configure( context.Configuration.GetSection("Kestrel")); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); });将以下基本配置添加到 appsettings.json 文件(Microsoft 文章中的更多配置选项): "Kestrel": { "EndPoints": { "Http": { "Url": "http://0.0.0.0:5002" }在您的项目中打开 CMD 或控制台 Publish/Debug/Release binaries 文件夹并运行: dotnet YourProject.dll 享受在 http://localhost:5002 上探索您的站点/api


M
Mwiza

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

只需运行命令:

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

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


M
Md Rafee

转到 properties/launchSettings.json 并找到您的应用程序名称,然后在此找到 applicationUrl。您会看到,它正在运行 localhost:5000,将其更改为您想要的任何内容。然后运行 dotnet run……欢呼


S
Sukesh Chand

我使用以下方法修复了 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

这被完全忽略了。仍在侦听另一个端口(不知道在哪里指定(。