如何在与默认端口不同的端口上公开 Web API? .NET 6

How do I expose Web API on different port than default? .NET 6

在端口 8888 上公开 .NET 6 Web API 的所有尝试都失败了。

我通过在 appsettings.json 中添加 url 并在 Program.cs 中配置端口,尝试了 和其他各种在线文章,但没有成功。

更新: Web API 在默认端口上启动,而不是在我想要将其公开的端口上启动。在 Program.cs 中配置端口时,我收到

System.InvalidOperationException: 'Changing the URL is not supported because Addresses IsReadOnly.'

app.Run("http://localhost:8888"); // This code results in Exception above

System.NotSupportedException: 'Collection was of a fixed size.'

app.Urls.Add("http://localhost:8888"); // The Exception above occurs after running this line of code

运行 下面的代码不改变端口,API 在默认端口

上启动
builder.WebHost.ConfigureKestrel(options => options.ListenLocalhost(8888));

添加行 builder.WebHost.ConfigureKestrel(options => options.ListenLocalhost(PortNumber)); 您的 Program.cs 文件应该允许您更改 .NET 6 网络上的默认端口 API。

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options => options.ListenLocalhost(8888));

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

以上更改在调试时也应该有效,但是另一个答案中提到的另一种在开发中更改此更改的方法,您可以使用解决方案属性文件夹下的 launchSettings.json 文件,文档可以找到与此文件相关的内容及其工作方式 here,您想要的示例如下:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:31312",
      "sslPort": 44346
    }
  },
  "profiles": {
    "ProfileNameHere": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:8887;http://localhost:8888",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

配置文件部分将影响开发环境中的 kestrel 端口,因此您应该将其更新为所需的值。您还可以创建具有不同端口和配置的多个配置文件。

本页已经记录了很多解决方案,您可以查看https://andrewlock.net/5-ways-to-set-the-urls-for-an-aspnetcore-app/

对我来说,

  • 当我使用 IDE 时,我修改了文件 Properties\launchSettings.json
  • 当我 运行 控制台中的应用程序时,我添加了参数 --urls "http://localhost:5100"
  • 当我在IIS上部署的时候,嗯,这不是问题,因为IIS总是让我输入端口。没有默认端口

注意:如果它们在您这边不起作用,请检查是否有错误。也许您可以重新启动您的 PC 以确保端口可用。

更新:

我已经尝试 运行 在端口 8888 并且一切正常(我也使用 .NET 6)

你能试试这个吗

 public class Program
        {
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)                 
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>).UseKestrel().UseUrls("http://0.0.0.0:8888");
                    });
        }

这也适用于 docker 环境。将端口设置为变量并作为下一步从环境中获取它