ASP.NET Core 选项模式通过 IOptions<T> 将 appsettings.json 配置绑定到强类型类,提升代码可维护性与类型安全;定义 SmtpSettings 类映射配置节,使用 Configure<SmtpSettings> 绑定,依赖注入获取值,并可通过数据注解或 FluentValidation 验证配置有效性。

ASP.NET Core 的选项模式通过依赖注入和强类型配置类,把应用的配置数据组织得更清晰、更安全。它不只是读取 appsettings.json 里的值,而是把配置映射到具体的 C# 类中,让代码更容易维护和测试。
要使用选项模式,先创建一个普通 C# 类来表示你的配置结构。这个类应该是简单的 POCO(Plain Old CLR Object)。
比如你有如下 JSON 配置:
appsettings.json{
"SmtpSettings": {
"Server": "smtp.example.com",
"Port": 587,
"Username": "user@example.com"
}
}对应定义一个选项类:
public class SmtpSettings
{
public string Server { get; set; }
public int Port { get; set; }
public string Username { get; set; }
}在 Program.cs 或 Startup.cs 中,使用 ConfigureServices 方法将配置绑定到选项类。
在 ASP.NET Core 6+ 的 Minimal API 风格中:
var builder = WebApplication.CreateBuilder(args);
<p>// 添加选项服务,并绑定到 SmtpSettings
builder.Services.Configure<SmtpSettings>(
builder.Configuration.GetSection("SmtpSettings")
);这样就把 appsettings.json 中的 "SmtpSettings" 节点自动映射到了 SmtpSettings 类上。
通过依赖注入获取配置值。推荐使用 IOptions<T> 接口。
public class EmailService
{
private readonly SmtpSettings _settings;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">public EmailService(IOptions<SmtpSettings> options)
{
_settings = options.Value;
}
public void Send()
{
Console.WriteLine($"Connecting to {_settings.Server}:{_settings.Port}");
}}
注册该服务:
builder.Services.AddTransient<EmailService>();
如果配置在运行时可能变化,可以使用 IOptionsSnapshot<T>(作用域内生效)或 IOptionsMonitor<T>(支持变更通知)。
你可以添加数据注解来验证选项是否正确加载。
using System.ComponentModel.DataAnnotations;
<p>public class SmtpSettings
{
[Required]
public string Server { get; set; }</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">[Range(1, 65535)]
public int Port { get; set; }
[EmailAddress]
public string Username { get; set; }}
然后在绑定后主动验证:
var configuration = builder.Configuration;
var smtpConfig = configuration.GetSection("SmtpSettings");
var settings = new SmtpSettings();
smtpConfig.Bind(settings);
<p>var validationContext = new ValidationContext(settings);
Validator.ValidateObject(settings, validationContext, validateAllProperties: true);或者用第三方库如 FluentValidation 实现更复杂的校验逻辑。
基本上就这些。选项模式让配置不再是零散的字符串查找,而是变成可测试、可验证、类型安全的对象模型,提升了整体代码质量。
以上就是ASP.NET Core 的选项模式如何管理配置?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号