Read AppSettings values from .json file in ASP.NET Core
Introduction
In ASP.NET Core, it is a common practice to store application settings in .json files. This article provides a comprehensive guide on how to read and access these values in an ASP.NET Core application.
Accessing AppSettings from a .json file
<code class="language-csharp">public Startup(IConfiguration configuration) { Configuration = configuration; }</code>
<code class="language-csharp">IConfigurationSection appSettingsSection = Configuration.GetSection("AppSettings");</code>
Example usage
To access specific values in "AppSettings":
<code class="language-csharp">string token = appSettingsSection["token"];</code>
Option Mode
ASP.NET Core 2.0 introduces options mode as the recommended method of accessing configuration settings. This mode allows you to bind configuration to a specific class.
<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>
Additional Notes
The above is the detailed content of How to Read AppSettings from a JSON File in ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!