通常我們在 Prgram.cs 中使用硬編碼的方式配置 ASP.NET Core 站點的 Hosting 環境,最常用的就是 .UseUrls() 。
public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseUrls("http://*:5000") .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); } }
但這種硬編碼綁定端口的方式會給在同一臺 Linux 服務器上部署多個站點造成麻煩,因為不同站點需要綁定不同的端口。除非你在開發時就已經約定好各個項目使用的端口,否則很容易在部署時遇到端口沖突問題,從而被迫修改代碼。
如果能通過配置文件設置綁定的端口,這個問題就迎刃而解。ASP.NET Core 中有沒有提供相應的解決之道呢?帶著這個問題,今天簽出 aspnet/Hosting 的源碼瀏覽一番,在 SampleStartups 的 StartupFullControl.cs 中找到了答案:
var config = new ConfigurationBuilder() .AddCommandLine(args) .AddEnvironmentVariables(prefix: "ASPNETCORE_") .AddJsonFile("hosting.json", optional: true) .Build(); var host = new WebHostBuilder() .UseConfiguration(config)
原來可以通過 hosting.json 進行配置,下面實際體驗一下。
首先創建一個 hosting.json 文件:
{ "server.urls": "http://*:5000;http://*:8001", "environment": "Development" }
上面的配置中除了配置 server.urls ,也順帶配置了一下 environment (默認是Production)。
然后在 Program.cs 中使用 hosting.json 中的配置:
public class Program { public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddJsonFile("hosting.json", optional: true) .Build(); var host = new WebHostBuilder() .UseUrls("http://*:5000") .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .UseConfiguration(config) .Build(); host.Run(); } }
注意一定要把上面的 .UseUrls() 刪除,不然 hosting.json 中的配置會被它覆蓋。
另外還要注意,在 project.json 中除了在 "publishOptions" 中添加 "hosting.json" ,還要在 "buildOptions" -> "copyToOutput" 中添加 "hosting.json",不然運行時在 bin 文件夾會找不到 hosting.json 文件。
"buildOptions": { "emitEntryPoint": true, "preserveCompilationContext": true, "copyToOutput": "hosting.json" }, "publishOptions": { "include": [ "hosting.json" ] }
最后用 dotnet run 命令運行站點,體驗一下實際效果。
Hosting environment: Development Content root path: C:\Dev\Cnblogs.WebDemo Now listening on: http://*:5000 Now listening on: http://*:8001 Application started. Press Ctrl+C to shut down.
【補充】ASP.NET Core 2.0 中的使用方法:
public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) { var config = new ConfigurationBuilder() .AddJsonFile("hosting.json", optional: true) .AddCommandLine(args) .Build(); return WebHost.CreateDefaultBuilder(args) .UseConfiguration(config) .UseStartup<Startup>() .Build(); } }
文章列表