在Visual Studio 2022中如何在Program.cs中添加IConfiguration及配置
在Visual Studio 2022的Program.cs中配置IConfiguration及自定义配置
1. 直接使用默认IConfiguration
.NET 6+项目采用顶级语句模式,WebApplication.CreateBuilder(args)会自动加载默认配置源(appsettings.json、环境变量、命令行参数等),无需额外初始化,直接通过builder.Configuration读取配置:
var builder = WebApplication.CreateBuilder(args); // 读取连接字符串 var dbConn = builder.Configuration.GetConnectionString("DefaultConnection"); // 读取层级配置 var appTitle = builder.Configuration["AppSettings:Title"];
2. 绑定自定义配置类
如果需要结构化管理配置,先定义对应配置类:
// AppSettings.cs public class AppSettings { public string Title { get; set; } public int MaxRequestTimeout { get; set; } public ExternalServices Services { get; set; } } public class ExternalServices { public string PaymentApiUrl { get; set; } public string AuthToken { get; set; } }
在Program.cs中绑定配置并注入到服务容器:
var builder = WebApplication.CreateBuilder(args); // 将配置节点绑定到自定义类,并注册为可注入选项 builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings")); // 可选:添加配置验证(需引用Microsoft.Extensions.Options) builder.Services.AddOptions<AppSettings>() .Bind(builder.Configuration.GetSection("AppSettings")) .Validate(settings => { return !string.IsNullOrEmpty(settings.Services.PaymentApiUrl); }, "支付API地址不能为空") .ValidateOnStart();
对应的appsettings.json配置示例:
{ "AppSettings": { "Title": "我的.NET应用", "MaxRequestTimeout": 30, "Services": { "PaymentApiUrl": "https://pay.example.com/api", "AuthToken": "xxxx-xxxx-xxxx" } } }
3. 在业务代码中使用配置
在控制器或服务中,通过IOptions<AppSettings>注入配置实例:
public class PaymentController : ControllerBase { private readonly AppSettings _config; public PaymentController(IOptions<AppSettings> configAccessor) { _config = configAccessor.Value; } [HttpPost] public async Task<IActionResult> ProcessPayment() { // 使用配置中的API地址 var apiUrl = _config.Services.PaymentApiUrl; // ...业务逻辑 return Ok(); } }
参考截图
Program.cs配置示例截图

(截图展示了上述绑定配置类的代码在Visual Studio 2022编辑器中的实际效果)
内容的提问来源于stack exchange,提问作者Bharath Kumar G
相关产品推荐
相关产品推荐

