我的AppConfig.json:

{
     "MyTimeZone: "CET",
     "RegularString" : "SomeValue",
     "AnArray" : ["1","2"]
}

我的POCO课程:

public class Settings
{
     public TimeZoneInfo MyTimeZone { get; set; }
     public string RegularString { get; set; }
     public IList<string> AnArray { get; set; }
}

注册处.反恐精英:

var configuration = GetConfiguration("AppSettings.json");
services.Configure<Settings>(configuration.GetSection("Settings"));

这当然不会将"CET"绑定到有效的TimeZoneInfo对象中.现在的问题是,在我的应用程序(一个web应用程序)中,从字符串转换为TimeZoneInfo的最佳位置是什么?有没有一种方法可以根据特定规则自动将字符串配置值转换为对象,而无需创建自定义转换器?

推荐答案

参考文献Use DI services to configure options

services.AddOptions<Settings>()
    .Configure<IConfiguration>((setting, configuration) => {
        var section = config.GetSection("Settings");
        //This will populate the other properties that can bind by default
        section.Bind(setting);

        //this will extract the remaining value and set it mnually
        string value = section.GetValue<string>("MyTimeZone");
        TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById(value);
        setting.MyTimeZone = info;
    });

复杂的设置值可以通过DI直接从配置中提取,用于创建时区并将其应用于设置.

Asp.net相关问答推荐

无法在Microsoft Windows Server 2016(数据中心)上运行.NET可移植性分析器

无法从部署在应用程序负载均衡器后面的 AWS ECS 上的应用程序发送 HTTP/S 请求

在 Web.Config 的 Location Path 元素中指定多个目录

如何向 Array.IndexOf 添加不区分大小写的选项

将 NUnit 添加到 ASP.NET MVC 测试框架的选项中

ASP.Net - App_Data & App_Code 文件夹?

使用实体框架从存储过程中获取数据

无法访问,内部,资源文件?

没有身份的 ASP.NET Core 2.0 承载身份验证

如何从 RouteData 获取路由名称?

从 C# AsyncCTP 使用 ExecuteReaderAsync 的任何缺点

更改后未应用 CSS

是否可以在 web.config 中添加响应 http 标头?

IIS 会话超时与 ASP.NET 会话超时

用于验证的数据注释,至少一个必填字段?

测试 Web 表单应用程序 (ASP.NET) 的最佳方法是什么

ASP.NET MVC Url Route 支持(点)

Asp.Net web 服务:我想返回错误 403 禁止

Page.IsPostBack 和 Page.IsCallBack 有什么区别?

使用 jQuery 从 asp:RadioButtonList 读取选定的值