Asp.net
將命令行參數傳遞給 ASP.NET Core 中的 Startup 類
我有通過命令行傳入的參數
private static int Main(string[] args) { const string PORT = "12345" ; var listeningUrl = $"http://localhost:{PORT}"; var builder = new WebHostBuilder() .UseStartup<Startup>() .UseKestrel() .UseUrls(listeningUrl); var host = builder.Build(); WriteLine($"Running on {PORT}"); host.Run(); return 0; }這些參數之一是日誌輸出目錄。如何將此值輸入我的
Startup班級,以便在收到請求時可以寫入此目錄?我想避免使用靜態類。提供價值的服務會是正確的方式嗎?如果是這樣,我如何將服務注入到我的中間件中?
您應該能夠使用
AddCommandLine()擴展程序。首先安裝 Nuget 包Microsoft.Extensions.Configuration.CommandLine並確保你有正確的導入:using Microsoft.Extensions.Configuration;現在更新您的
Main方法以包含新配置:var config = new ConfigurationBuilder() .AddJsonFile("hosting.json", optional: true) //this is not needed, but could be useful .AddCommandLine(args) .Build(); var builder = new WebHostBuilder() .UseConfiguration(config) //<-- Add this .UseStartup<Startup>() .UseKestrel() .UseUrls(listeningUrl);現在您將命令行選項視為配置:
dotnet run /MySetting:SomeValue=123並讀入程式碼:
var someValue = Configuration.GetValue<int>("MySetting:SomeValue");