ASP.NET 配置
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 ASP.NET 8 中的配置。配置对于跨不同环境管理应用程序设置至关重要。
ASP.NET 提供了一个灵活的配置系统,可以与 JSON 文件、环境变量和命令行参数等各种源配合使用。
基本定义
ASP.NET 中的配置是指管理应用程序设置的系统。这些设置可以存储在不同的源中并统一访问。
配置系统围绕 `IConfiguration` 接口构建。它提供了从各种提供程序读取配置值的方法。
配置值可以使用节进行分层组织。该系统支持将配置值绑定到强类型对象。
常见的配置源包括 `appsettings.json`、环境变量、用户机密和命令行参数。可以组合使用多个源。
使用 `WebApplication.CreateBuilder()` 创建新的 ASP.NET 应用程序时,会自动设置配置系统。
ASP.NET 配置示例
以下示例演示了如何在 ASP.NET 8 应用程序中使用配置。
appsettings.json
{ "AppSettings": { "Title": "Product Catalog", "MaxItems": 50, "Enabled": true, "ApiSettings": { "BaseUrl": "https://api.example.com", "Timeout": 30 } }, "ConnectionStrings": { "DefaultConnection": "Server=localhost;Database=Products;Trusted_Connection=True;" } }
此 JSON 配置文件以分层结构定义了应用程序设置。它既包括简单值,也包括嵌套对象。
Program.cs
var builder = WebApplication.CreateBuilder(args); // Add services to the container builder.Services.AddControllers(); // Bind configuration to strongly-typed objects builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings")); var app = builder.Build(); app.MapControllers(); // Access configuration directly var config = app.Services.GetRequiredService<IConfiguration>(); var title = config["AppSettings:Title"]; Console.WriteLine($"Application Title: {title}"); app.Run(); public class AppSettings { public string Title { get; set; } public int MaxItems { get; set; } public bool Enabled { get; set; } public ApiSettings ApiSettings { get; set; } } public class ApiSettings { public string BaseUrl { get; set; } public int Timeout { get; set; } }
此代码设置配置绑定,并演示了访问配置值的不同方法。`Configure` 方法将设置绑定到类。
Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; [ApiController] [Route("[controller]")] public class ProductsController : ControllerBase { private readonly IConfiguration _config; private readonly AppSettings _appSettings; private readonly string _connectionString; public ProductsController(IConfiguration config, IOptions<AppSettings> appSettings) { _config = config; _appSettings = appSettings.Value; _connectionString = _config.GetConnectionString("DefaultConnection"); } [HttpGet("settings")] public IActionResult GetSettings() { var settings = new { Title = _appSettings.Title, MaxItems = _appSettings.MaxItems, ApiUrl = _appSettings.ApiSettings.BaseUrl, ConnectionString = _connectionString }; return Ok(settings); } [HttpGet("config-example")] public IActionResult GetConfigExample() { var timeout = _config["AppSettings:ApiSettings:Timeout"]; var enabled = _config.GetValue<bool>("AppSettings:Enabled"); return Ok(new { Timeout = timeout, Enabled = enabled }); } }
控制器演示了访问配置的三种方法:通过 `IConfiguration`、强类型选项和连接字符串。每种方法都有不同的用例。
对于复杂场景,首选强类型选项模式 (`IOptions<T>`)。直接访问 `IConfiguration` 对于简单值或动态访问很有用。
来源
在本文中,我们探讨了 ASP.NET 8 中的配置系统。这个强大的功能提供了管理应用程序设置的灵活方式。