asp .net core 配置 (应用设置)
一、基础
IConfiguration 注入
private readonly IConfiguration _configuration; public HomeController(IConfiguration configuration) { _configuration = configuration; }
二、获取值
1、单层
a、[ ]
_configuration["Test1"]
b、GetValue
_configuration.GetValue<string>("Test1", "No")
2、分层
a、原始([ ] 或 GetValue)
ViewBag.Id = _configuration.GetValue<string>("MsgApi:Id", "NoId"); ViewBag.Secret = _configuration["MsgApi:Secret"];
b、优化(GetSection)
IConfigurationSection section = _configuration.GetSection("MsgApi"); ViewBag.Id = section.GetValue<string>("Id", "No Id"); ViewBag.Secret = section.GetValue<string>("Secret", "No Secret");
3、选项模式
a、创建Model
public class MsgOptions { public string? Id { get; set; } public string? Secret { get; set; } }
b、应用(Get 或 Bind)
MsgOptions? options = _configuration.GetSection("MsgApi").Get<MsgOptions>(); ViewBag.Id = options?.Id; ViewBag.Secret = options?.Secret;
注意:Bind 要提前创建对象
三、高级
1、服务
a、服务
builder.Services.AddOptions<MsgOption>().BindConfiguration("MsgApi");
builder.Services.Configure<MsgOptions>(builder.Configuration.GetSection("MsgApi"));
b、应用
private readonly MsgOptions _options; public HomeController(IOptions<MsgOptions> msgOptions) { _options = msgOptions.Value; } ViewBag.Id = _options.Id; ViewBag.Secret = _options.Secret;
2、环境(Development、Staging、Production)
3、密钥管理器(项目右击)
4、环境变量(终端)
$Env: a__b="ab"
$Env:c__d="cd"
5、自定义json配置
builder.Configuration.AddJsonFile(path: "weather.json", optional: true, reloadOnChange: true);

浙公网安备 33010602011771号