Home >Backend Development >C++ >How to Read AppSettings Values from a JSON File in ASP.NET Core?
External configuration sources, like JSON files, are frequently used in web development. ASP.NET Core offers robust methods for accessing this data, differing from older versions. This guide demonstrates how to retrieve AppSettings values from a JSON file.
First, create a Config.json
file (e.g., within the appsettings
folder) with your key-value pairs:
<code class="language-json">{ "AppSettings": { "token": "1234" } }</code>
This file stores the configuration data you'll access in your code.
Within your application's Startup.cs
file, configure the ConfigurationBuilder
:
<code class="language-csharp">public class Startup { public IConfiguration Configuration { get; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings/Config.json", optional: true, reloadOnChange: true); Configuration = builder.Build(); } // ... rest of your Startup class }</code>
To use these settings in your controllers, inject the IConfiguration
object:
<code class="language-csharp">public class HomeController : Controller { private readonly IConfiguration _configuration; public HomeController(IConfiguration configuration) { _configuration = configuration; } public IActionResult Index() { var token = _configuration["AppSettings:token"]; return View(token); } }</code>
Retrieving the value is straightforward using the key path "AppSettings:token".
For ASP.NET Core 2.0 and later, the Options pattern provides a more structured approach.
Define a class representing your configuration:
<code class="language-csharp">public class AppSettings { public string Token { get; set; } }</code>
In Startup.cs
, configure and inject the IOptions<AppSettings>
object:
<code class="language-csharp">services.AddOptions<AppSettings>() .Configure<IConfiguration>((settings, configuration) => { configuration.GetSection("AppSettings").Bind(settings); });</code>
Now, in your controller:
<code class="language-csharp">public class HomeController : Controller { private readonly IOptions<AppSettings> _appSettings; public HomeController(IOptions<AppSettings> appSettings) { _appSettings = appSettings; } public IActionResult Index() { var token = _appSettings.Value.Token; return View(token); } }</code>
This method offers type safety and improved maintainability compared to the previous approach. It's the preferred method for newer ASP.NET Core projects.
The above is the detailed content of How to Read AppSettings Values from a JSON File in ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!