惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
有赞技术团队
有赞技术团队
L
LangChain Blog
C
Check Point Blog
博客园 - 【当耐特】
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
美团技术团队
博客园 - 司徒正美
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏
S
SegmentFault 最新的问题
A
About on SuperTechFans
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
博客园 - 叶小钗
腾讯CDC
B
Blog
G
Google Developers Blog
The Cloudflare Blog
P
Proofpoint News Feed

博客园 - 桂素伟

Semantic Kernel:开启MCP Semantic Kernel:Phi-4 mini的tools .NET10:解决json序列化时引用自己 .NET10:字符数字 Semantic Kernel:接入本地deepseek-r1:1.5b Semantic Kernel:接入azure中的deepseek-r1 C#中的Channel .NET9中基于策略角色验证的包冲突 Semantic Kernel:OpenAPI的Plugin Semantic Kernel:Phi-4试用 AI应用开发的浅见 Semantic Kernel:Process Semantic Kernel:新Agent代理 UnitsNet 库简介 .NET9里WinForm更新了什么 SemanticKernel系列,AI系列,SmartFill介绍视频系列 更流畅的asp.net api的错误返回 用.srt字幕文件生成.wav语音 自制实时翻译小工具
.NET9中使用Options
桂素伟 · 2025-03-02 · via 博客园 - 桂素伟

  选项模式在 ASP.NET Core 中使用类来提供对相关配置设置的强类型访问。通过将配置设置隔离到单独的类,应用程序遵循封装和关注点分离的原则。封装确保依赖于配置的类仅依赖于其使用的设置;关注点分离则确保应用的不同部分的设置互不依赖或耦合。此外,选项模式还提供了验证配置数据的机制。

  • 三种IOptions:

下面是代码文件:

Program.cs

using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOptions<Setting>().BindConfiguration("Setting");

var app = builder.Build();

app.Services.GetService<IOptionsMonitor<Setting>>()?.OnChange((setting, name) =>
{
    app.Logger.LogInformation(setting.Value);
});


app.MapGet("/opt1", (IOptions<Setting> option) =>
{
    app.Logger.LogInformation("opt1");
    return option.Value;
});
app.MapGet("/opt2", (IOptionsSnapshot<Setting> option) =>
{
    app.Logger.LogInformation("opt2");
    return option.Value;
});
app.MapGet("/opt3", (IOptionsMonitor<Setting> option) =>
{
    app.Logger.LogInformation("opt3");

    return option.CurrentValue;
});
app.Run();


class Setting
{
    public string Name { get; set; }
    public string Value { get; set; }
}

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Setting": {
    "Name": "key",
    "Value": "1234567890"
  }
}

OptionDemo.http

@OptionDemo_HostAddress = http://localhost:5064

GET {{OptionDemo_HostAddress}}/opt1
Accept: application/json

###

GET {{OptionDemo_HostAddress}}/opt2
Accept: application/json

###

GET {{OptionDemo_HostAddress}}/opt3
Accept: application/json

###

打开OptionDemo.http,点击Opt1,Opt2,Opt3的“发送请求”,结果如下:

   把 appsettings.json中的Setting的Value改成“1234567890ABCD”,结果如下:

 请求Opt1结果:

 请求Opt2结果:

 请求Opt3结果:

  • 验证:

可以通过Validate()方法对Options进行验证,目前有两种验证点,一个是服务启动时,即有ValidateOnStart方法;另外一种是在使用这个Options时,即不写ValidateOnStart方法。

builder.Services.AddOptions<Setting>()
    .BindConfiguration("Setting")
    .ValidateOnStart<Setting>()
    .Validate(setting =>
    {
        return !string.IsNullOrWhiteSpace(setting.Name) && !string.IsNullOrWhiteSpace(setting.Value);       
    }, "Setting配置有误");

触发错误如下:

   利用Validate是自定义验证,当然也可以利用DataAnnotations进行验证,代码如下:

builder.Services.AddOptions<Setting>()
    .BindConfiguration("Setting")
    .ValidateDataAnnotations();

触发错误如下:

   文章来源微信公众号

  想要更快更方便的了解相关知识,可以关注微信公众号 

****欢迎关注我的asp.net core系统课程****
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524