asp.net core发布配置端口号,支持linux

发布于:2024-12-22 ⋅ 阅读:(15) ⋅ 点赞:(0)

方式一,修改配置文件 appsettings.json

找到文件 appsettings.json,
添加如下节点配置,在linux环境需要设置0.0.0.0才可以正常代表本机,然后被其他机器访问,此处设置端口8000,

  "Kestrel": {
    "Endpoints": {
      "MyHttpEndpoint": {
        "Url": "http://0.0.0.0:8000"
      }
    }
  }

或者

  ,"Kestrel": {
    "Endpoints": {
      "MyHttpEndpoint": {
        //0.0.0.0,或* 有效用于linux、windows
        // "Url": "http://0.0.0.0:8000"             
        "Url": "http://*:8000"
      }
    }
  }

appsettings.json 完整代码参考:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
  ,"Kestrel": {
    "Endpoints": {
      "MyHttpEndpoint": {
        //0.0.0.0,或* 有效用于linux、windows
        // "Url": "http://0.0.0.0:8000"             
        "Url": "http://*:8000"
      }
    }
  }
}

方式二,代码添加端口:

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel((context, serverOptions) =>
{
    serverOptions.Listen(IPAddress.Loopback, 5900);
    serverOptions.Listen(IPAddress.Loopback, 5901, listenOptions =>
    {
        listenOptions.UseHttps("testCert.pfx", "testPassword");
    });
});

微软帮助文档
https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/servers/kestrel/endpoints?view=aspnetcore-9.0#specify-ports-only