默认状况下,ASP.NET Core应用程序监听如下URL:web
在这篇文章中,我展现了5种不一样的方式来更改您的应用程序监听的URL。shell
UseUrls()
DOTNET_URLS
或者 ASPNETCORE_URLS
--urls
Listen()
手动使用配置Kestrel服务器的地址我将在下面更详细地介绍每一个选项。json
设置绑定URL的第一个也是最简单的方法,在配置IWebHostBuilder
的时候使用UseUrls()
进行硬编码。windows
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:5003", "https://localhost:5004"); }); }
.NET Core使用两种类型的配置:bash
若是您同时设置了这两个环境变量,那么ASPNETCORE_URLS参数优先。服务器
您能够用不一样的方式设置环境变量。例如,使用命令行:app
setx ASPNETCORE_URLS "http://localhost:5001"
使用powershellsocket
$Env: ASPNETCORE_URLS = "http://localhost:5001"
使用bash:oop
export ASPNETCORE_URLS="http://localhost:5001;https://localhost:5002"
如上所示,您还能够经过使用分号分隔多个地址来传递多个地址以进行监听(使用HTTP或HTTPS)。ui
设置主机配置值的另外一种方法是使用命令行。若是设置了命令行参数,那么会覆盖环境变量的值, 只需使用--urls
参数:
dotnet run --urls "http://localhost:5100"
和上面同样,您能够经过使用分号将多个URL分开来设置多个URL:
dotnet run --urls "http://localhost:5100;https://localhost:5101"
环境变量和命令行参数多是在生产环境中为应用程序设置URL的最多见方法,可是它们对于本地开发来讲有点麻烦。一般使用launchSettings.json会更容易。
大多数 .NET项目模板在Properties文件夹中都包含launchSettings.json文件,这个文件包含了启动.NET Core应用程序的各类配置文件。
{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:38327", "sslPort": 44310 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "TestApp": { "commandName": "Project", "launchBrowser": true, "applicationUrl": "https://localhost:5001;http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
launchSettings.json还提供了environmentVariables参数,您能够用它来设置环境变量,就像上面这样,而后咱们能够选择不一样的启动类型:
默认状况下,几乎全部的.NET Core应用程序都配置了Kestrel,若是须要,您能够手动配置Kestrel的端点,也能够配置KestrelServerOptions。
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.UseKestrel(opts => { // Bind directly to a socket handle or Unix socket // opts.ListenHandle(123554); // opts.ListenUnixSocket("/tmp/kestrel-test.sock"); opts.Listen(IPAddress.Loopback, port: 5002); opts.ListenAnyIP(5003); opts.ListenLocalhost(5004, opts => opts.UseHttps()); opts.ListenLocalhost(5005, opts => opts.UseHttps()); }); }); }
我我的没有以这种方式在Kestrel中设置监听端点,可是很高兴知道能够根据须要彻底控制Kestrel。
在这篇文章中,我展现了五种不一样的方式来设置应用程序监听的URL。UseUrls()是最简单的一种,但一般不适合在生产中使用, launchSettings.json文件是在开发环境中设置的URL是很是有用的。 在生产中咱们一般使用命令行参数--urls或者环境变量ASPNETCORE_URLS和DOTNET_URLS, 但愿对您有帮助。
原文连接: https://andrewlock.net/5-ways-to-set-the-urls-for-an-aspnetcore-app/
欢迎扫码关注咱们的公众号 【全球技术精选】,专一国外优秀博客的翻译和开源项目分享,也能够添加QQ群 897216102