Kestrel 服务器使用的默认配置文件是hosting.json。该名称在不同的 beta 版本中多次更改。如果您现在使用 project.json 和以下 "command" 部分
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel"
}
然后在通过命令行启动服务器时
dnx web
将读取文件hosting.json。文件
{
"server.urls": "http://0.0.0.0:5000"
}
将配置服务器在每个 IP4 地址上侦听 5000。配置
{
"server.urls": "http://::5000;http://0.0.0.0:5000"
}
将通知在 IP4 和 IP6 地址上侦听 5000。
可以通过使用ASPNET_ENV 环境变量或使用--config myconfig1.json(或config=myconfig1.json)来指定替代配置文件。例如,您可以使用
SET ASPNET_ENV=Development
并创建具有特定配置的hosting.Development.json 文件。或者,您可以使用 project.json 和
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel"
"webProd": "Microsoft.AspNet.Server.Kestrel --config prod.json"
}
并按使用情况启动服务器
dnx webProd
我必须另外提醒,可能需要您允许额外收听和注册(启动dnx web)。由于防火墙和侦听新 TCP/HTTP 端口的本地安全性,它是必需的。像下面这样的东西应该为每个人(IPv4 和 IPv6)进行本地注册和监听 5000 端口:
netsh http add iplisten ipaddress=0.0.0.0:5000
netsh http add iplisten ipaddress=::5000
netsh http add urlacl url=http://+:5000/ user=\Everyone
为了更安全,您可以调整上述配置以授予最小权限。
更新:感谢@BlaneBunderson。可以使用 * 代替 IP 地址(如 http://*:5000)从任何接口监听 any IP4 和 IP6 地址。一个人应该小心,不要使用这些
http://*:5000;http://::5000
http://::5000;http://*:5000
http://*:5000;http://0.0.0.0:5000
-
http://*:5000;http://0.0.0.0:5000
因为它需要注册IP6地址::或IP4地址0.0.0.0两次。
对应the announcement
从技术上讲,任何不是“localhost”或有效 IPv4 的主机名或
IPv6 地址将导致 Kestrel 绑定到所有网络接口。
我认为将来可能会改变这种行为。因此,我建议仅使用*:5000、0.0.0.0:5000 和::5000 表格来注册任何 IT 地址。
更新 2: ASP.NET Core RC2 更改(请参阅the announcement)加载默认值的行为。必须在Main 中进行更改才能从hosting.json 和命令行参数加载设置。下面是一个使用示例
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("hosting.json", optional: true)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.AddCommandLine(args)
.Build();
var host = new WebHostBuilder()
.UseUrls("http://*:1000", "https://*:1234", "http://0.0.0.0:5000")
.UseEnvironment("Development")
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
上面的代码默认使用了三个绑定:"http://*:1000"、"https://*:1234"、"http://0.0.0.0:5000",而不是默认使用默认端口5000(确切地说是http://localhost:5000的使用)。 .UseConfiguration(config) 的调用是在 .UseUrls 之后进行的。因此,从hosting.json 或命令行加载的配置会覆盖默认选项。如果删除.SetBasePath(Directory.GetCurrentDirectory()) 行,则hosting.json 将从编译应用程序dll 的同一目录加载(例如bin\Debug\netcoreapp1.0)。
可以像这样使用执行
dotnet.exe run --server.urls=http://0.0.0.0:5000
覆盖默认设置(来自UseUrls)和来自hosting.json 的"server.urls" 属性的设置(如果存在)。
同样可以通过设置环境变量来覆盖 ULR 设置
set ASPNETCORE_SERVER.URLS=http://localhost:12541/
那么使用dotnet.exe run的应用程序默认启动将使用http://localhost:12541/进行绑定。
您可以找到here 使用 HTTPS 绑定的示例。
备注: ASP.NET 后续版本环境变量名称由ASPNETCORE_SERVER.URLS 改为ASPNETCORE_URLS(参见here ASP.NET Core 3.1 的文档)。