Home >Backend Development >C++ >How to Access Configuration Values from appsettings.json in ASP.NET Core?
To access configuration data stored in the appsettings.json file in ASP.NET Core, you can use the configuration builder or options mode.
Method 1: Use ConfigurationBuilder.GetValue
Method 2: Use ConfigurationBinder
1. Define configuration class
2. Register configuration instance
3. Inject IOptions
appsettings.json:
<code class="language-json">{ "ConnectionStrings": { "DefaultConnection": "Server=localhost;Database=MyDatabase" }, "AppIdentitySettings": { "User": { "RequireUniqueEmail": true }, "Password": { "RequiredLength": 8 } } }</code>
Startup.cs:
<code class="language-csharp">public void ConfigureServices(IServiceCollection services) { var connectionStringSection = Configuration.GetSection("ConnectionStrings"); services.Configure<ConnectionStringSettings>(connectionStringSection); var appIdentitySettingsSection = Configuration.GetSection("AppIdentitySettings"); services.Configure<AppIdentitySettings>(appIdentitySettingsSection); }</code>
Controller.cs:
<code class="language-csharp">public class HomeController : Controller { private readonly AppIdentitySettings _appIdentitySettings; public HomeController(IOptions<AppIdentitySettings> appIdentitySettings) { _appIdentitySettings = appIdentitySettings.Value; } public IActionResult Index() { var requiredLength = _appIdentitySettings.Password.RequiredLength; // ... } }</code>
Please note that ConnectionStringSettings
and AppIdentitySettings
in the above code snippet require you to define the corresponding C# classes to match the structure in appsettings.json
. These two methods provide flexible ways to access your application configuration. Which method you choose depends on your preference and the complexity of your application.
The above is the detailed content of How to Access Configuration Values from appsettings.json in ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!