前言
默认情况下,ASP.NET Core使用下列2个启动地址:
http://localhost:5000
https://localhost:5001
同时,我们也可以通过配置或代码方式修改启动地址。
那么,这几种修改方式都是什么?谁最后起作用呢?
设置方法 1.applicationUrl属性launchSettings.json文件中的applicationUrl
属性,但是仅在本地开发计算机上使用:
"profiles": {
"WebApplication1": {
...
"applicationUrl": "http://localhost:5100",
}
}
2.环境变量
环境变量ASPNETCORE_URLS
,有多个设置位置,下面演示的是使用launchSettings.json文件:
"profiles": {
"WebApplication1": {
...
"environmentVariables": {
"ASPNETCORE_URLS": "http://localhost:5200"
}
}
}
3.命令行参数
命令行参数--urls
,有多个设置位置,下面演示的是使用launchSettings.json文件:
"profiles": {
"WebApplication1": {
...
"commandLineArgs": "--urls http://localhost:5300",
}
}
4.UseUrls方法
修改ConfigureWebHostDefaults方法:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
webBuilder.UseUrls("http://localhost:5400");
});
5.UseKestrel方法
修改ConfigureWebHostDefaults方法:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
webBuilder.UseKestrel(options=> options.ListenLocalhost(5500, opts => opts.Protocols = HttpProtocols.Http1));
});
优先级
通过将上述设置方式进行组合,发现优先级顺序如下:
-
UseKestrel
方法 -
命令行参数
--urls
-
UseUrls
方法 -
环境变量
ASPNETCORE_URLS
-
applicationUrl属性
-
默认值
如果在同一台机器上运行多个ASP.NET Core实例,使用默认值肯定不合适。
由于UseKestrel
方法不能被覆盖,而环境变量ASPNETCORE_URLS
容易造成全局影响。
建议:开发时通过UseUrls
方法指定默认启动地址,使用命令行参数--urls
运行时修改启动地址。