ASP.NET IConfiguration
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 ASP.NET 8 中的 IConfiguration 接口。该接口提供了一种统一的方式来访问各种来源的配置值。
ASP.NET Core 的配置系统非常灵活且可扩展。它可以从 JSON 文件、环境变量、命令行参数等读取配置数据。
基本定义
IConfiguration 是在 ASP.NET 中处理配置的主要接口。它提供了将配置值读取为字符串、数字或复杂对象的方法。
ASP.NET Core 中的配置系统遵循分层结构。可以使用冒号分隔的键来访问值,这些键代表层次结构路径。
IConfiguration 会自动注册到依赖注入容器中。它可以注入到控制器、服务或其他需要配置值的组件中。
ASP.NET IConfiguration 示例
下面的示例演示了如何在 ASP.NET 8 应用程序中使用 IConfiguration。
appsettings.json
{
"AppSettings": {
"Title": "Product Catalog",
"MaxItems": 50,
"Enabled": true,
"ConnectionStrings": {
"Default": "Server=localhost;Database=Products;Trusted_Connection=True;"
}
}
}
此 JSON 配置文件定义了具有各种值类型的应用程序设置。分层结构通过嵌套对象表示。
Program.cs
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); var app = builder.Build(); app.MapControllers(); app.Run();
默认的 WebApplication 生成器会自动从 appsettings.json、环境变量和命令行参数加载配置。
Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly IConfiguration _configuration;
private readonly AppSettings _settings;
public ProductsController(IConfiguration configuration,
IOptions<AppSettings> settings)
{
_configuration = configuration;
_settings = settings.Value;
}
[HttpGet("config")]
public IActionResult GetConfig()
{
// Direct access to configuration
var title = _configuration["AppSettings:Title"];
var maxItems = _configuration.GetValue<int>("AppSettings:MaxItems");
// Strongly-typed access
return Ok(new {
ConfigTitle = title,
ConfigMaxItems = maxItems,
SettingsTitle = _settings.Title,
SettingsEnabled = _settings.Enabled,
ConnectionString = _settings.ConnectionStrings.Default
});
}
}
public class AppSettings
{
public string Title { get; set; }
public int MaxItems { get; set; }
public bool Enabled { get; set; }
public ConnectionStrings ConnectionStrings { get; set; }
}
public class ConnectionStrings
{
public string Default { get; set; }
}
此控制器演示了两种访问配置值的方法。第一种方法直接使用 IConfiguration 读取值。第二种方法使用 IOptions 通过强类型配置。
Program.cs (附加配置)
var builder = WebApplication.CreateBuilder(args);
// Configure strongly-typed settings
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
Configure 方法将 AppSettings 部分绑定到 AppSettings 类。这使得在整个应用程序中注入强类型配置成为可能。
该示例展示了直接配置访问和首选的强类型方法。IOptions 模式提供了编译时安全性和更好的可测试性。
来源
在本文中,我们探讨了 ASP.NET 8 中的 IConfiguration 接口。这项强大的功能提供了对来自多个来源的配置值的灵活访问。