在 ASP.NET Core 中從 .json 檔案讀取 AppSettings 值
簡介
在 ASP.NET Core 中,將應用程式設定儲存在 .json 檔案中是常見的做法。本文將提供一個全面的指南,介紹如何在 ASP.NET Core 應用程式中讀取和存取這些值。
從 .json 檔案存取 AppSettings
<code class="language-csharp">public Startup(IConfiguration configuration) { Configuration = configuration; }</code>
<code class="language-csharp">IConfigurationSection appSettingsSection = Configuration.GetSection("AppSettings");</code>
範例用法
要存取「AppSettings」中的特定值:
<code class="language-csharp">string token = appSettingsSection["token"];</code>
選項模式
ASP.NET Core 2.0 引入了選項模式,作為存取配置設定的建議方法。此模式可讓您將配置綁定到特定類別。
<code class="language-csharp">public class MyConfig { public string Token { get; set; } }</code>
<code class="language-csharp">public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.Configure<MyConfig>(Configuration.GetSection("AppSettings")); }</code>
<code class="language-csharp">public class MyController : Controller { private readonly MyConfig _appSettings; public MyController(IOptions<MyConfig> appSettings) { _appSettings = appSettings.Value; } string GetToken() => _appSettings.Token; }</code>
附加說明
以上是如何在 ASP.NET Core 中從 JSON 檔案讀取 AppSettings?的詳細內容。更多資訊請關注PHP中文網其他相關文章!