我的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相关问答推荐

C# - 将 xyz 平铺转换为纬度/经度,反之亦然,给出不同的结果

ASP.Net - App_Data & App_Code 文件夹?

为 Web 请求实现速率限制算法的最佳方法是什么?

为什么 ASP.NET Identity 2.0 使用 GUID/字符串作为用户 ID?

如何缓存数据库表以防止在 Asp.net C# mvc 中出现许多数据库查询

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

文本框的输入按键触发事件

问题映射 HttpHandler --> HTTP Error 404 Not Found

HTTP 错误 503.该服务在简单的 ASP.NET 4.0 网站下不可用

Razor 主机工厂错误

ASP.NET 中的 <%# Bind("") %> 和 <%# Eval("") %> 有什么区别?

带有完整内存错误的 WCF 服务(内存门判断失败,因为可用内存) - 如何解决

您如何在 .net WebApi2 应用程序中的 OAuth2 令牌请求中使用额外参数

如何从 NuGet 安装 EntityFramework 5.0(和其他旧版本)?

HttpResponse.End 或 HttpResponse.Close 与 HttpResponse.SuppressContent

ASP.NET 5、EF 7 和 SQLite - SQLite 错误 1:没有这样的表:博客

elmah:没有 HttpContext 的异常?

在控制器 asp.net-core 中获取当前区域性

Unity 中的单例每个调用上下文(Web 请求)

如何识别字符串是否包含 unicode 字符?