通常 asp.net core 启动直接启动是这样的:
➜ AspNetCoreWebApiContribProtobufSample git:(master) ✗ dotnet run info: Microsoft.Hosting.Lifetime[0] Now listening on: http://localhost:31005 info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down. info: Microsoft.Hosting.Lifetime[0] Hosting environment: Development info: Microsoft.Hosting.Lifetime[0]
3.0 后asp.net core 有 5 种方式设置 url
UseUrls()
-在 Program.cs 中设置静态使用的url。- 环境变量——使用 DOTNET_URLS 或 ASPNETCORE_URLS 设置 url。
- 命令行参数——在从命令行运行时使用——URLs参数设置url。
- 使用launchSettings.json——使用 applicationUrl 属性设置url。
KestrelServerOptions.Listen()
——使用Listen()
手动配置 Kestrel server 的地址。
UseUrls()
这种是一种硬编码的方式,实际情况中很少使用。
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>();
webBuilder.UseUrls("http://localhost:5011");
});
}
环境变量的方式
环境变量有两种配置方式:
App configuration 应用通用配置,直接从 appsettings.{**env.EnvironmentName**}.json ,添加
urls
节点{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "urls": "http://*:5012" }
Host configuration 从通用配置中加载(这种方式很少用)
setx ASPNETCORE_URLS "http://localhost:5001" #powershell $Env: ASPNETCORE_URLS = "http://localhost:5001"
命令行参数
形式如下:
dotnet run --urls "http://localhost:5100" dotnet run --urls "http://localhost:5100;https://localhost:5101" dotnet xxx.dll --urls "http://*:5100"
launchSettings.json
这种方式广泛应用于开发阶段。
KestrelServerOptions.Listen()
直接上代码:
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>();
// webBuilder.UseUrls("http://localhost:5011");
webBuilder.UseKestrel(opts =>
{
opts.ListenLocalhost(5014, opts => opts.UseHttps());
opts.ListenLocalhost(5015, opts => opts.UseHttps());
});
});
}
关注
webBuilder.UseKestrel(opts =>
{
opts.ListenLocalhost(5014, opts => opts.UseHttps());
opts.ListenLocalhost(5015, opts => opts.UseHttps());
});
这种方式也不经常用。
总结
生效的优先级:
从高到底
KestrelServerOptions > Command line arguments > 环境变量 > UseUrls() > launchSettings.json
适用条件
- KestrelServerOptions 、UseUrls()、属于硬编码,适用于开发阶段,个人调试等环节。
- launchSettings.json 通用开发环境。
- 环境变量 适合服务器部署,生产环境
- Command line arguments 适合线上环境、docker部署生产环境等