方式一,修改配置文件 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