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
public Startup(IConfiguration configuration) { Configuration = configuration; }
IConfigurationSection appSettingsSection = Configuration.GetSection("AppSettings");
Example usage
To access specific values in "AppSettings":
string token = appSettingsSection["token"];
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.
public class MyConfig { public string Token { get; set; } }
public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.Configure<MyConfig>(Configuration.GetSection("AppSettings")); }
public class MyController : Controller { private readonly MyConfig _appSettings; public MyController(IOptions<MyConfig> appSettings) { _appSettings = appSettings.Value; } string GetToken() => _appSettings.Token; }
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!