gpt4 book ai didi

c# - 是否可以将配置绑定(bind)到 .NET Core 中的无状态/只读模型?

转载 作者:太空狗 更新时间:2023-10-29 23:05:19 26 4
gpt4 key购买 nike

通常,我们会有一些模型

public class ConnectionStrings
{
public string Sql { get; set; }
public string NoSql { get; set; }
}

然后我们在 appsettings.json 中有如下内容:

"ConnectionStrings": {
"Sql": "some connection string",
"NoSql": "some other connection string"
}

然后我绑定(bind)模型如下:

services.Configure<ConnectionStrings>(
options => Configuration.GetSection("ConnectionStrings").Bind(options));

一切都很完美,但我的模型可变没有意义,因为它包含重要信息。毕竟,配置是静态信息,所以一旦我的模型被读取,它应该保持原样。

还有其他更安全的方法吗?

最佳答案

作为替代方案,对于 version 2.1+ ,您现在可以通过指定使用 BinderOptions 来绑定(bind)到非公共(public)属性:

services.Configure<ConnectionStrings>(options => 
Configuration.GetSection("ConnectionStrings")
.Bind(options, c => c.BindNonPublicProperties = true));

或者只是获取它们:

var connectionStrings = Configuration.GetSection("ConnectionStrings")
.Get<ConnectionStrings>(c => c.BindNonPublicProperties = true);

关于c# - 是否可以将配置绑定(bind)到 .NET Core 中的无状态/只读模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45378143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com