c# - 是否有内置方法来序列化数组配置值?

标签 c# visual-studio-2015 asp.net-core-mvc config.json

我正在进行一个新的 ASP.NET 5 项目。

我正在尝试读取存储在我的 config.json 文件中的数组值,如下所示:

{
  "AppSettings": {
    "SiteTitle": "MyProject",
    "Tenants": {
      "ReservedSubdomains": ["www", "info", "admin"]
    }
  },
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-MyProject....."
    }
  }
}

如何从我的 C# 代码访问它?

最佳答案

至少在 config.json 中不支持 beta4 数组。请参阅ASP.NET issue 620 。但您可以使用以下 config.json:

"AppSettings": {
  "SiteTitle": "MyProject",
  "Tenants": {
    "ReservedSubdomains": "www, info, admin"
  }
}

并将其映射到这样的类:

public class AppSettings
{
  public string SiteTitle { get; set; }
  public AppSettingsTenants Tenants { get; set; } = new AppSettingsTenants();
}

public class AppSettingsTenants
{
  public string ReservedSubdomains { get; set; }
  public List<string> ReservedSubdomainList
  {
     get { return !string.IsNullOrEmpty(ReservedSubdomains) ? ReservedSubdomains.Split(',').ToList() : new List<string>(); }
  }
}

然后可以将其注入(inject)到 Controller 中:

public class MyController : Controller
{
  private readonly AppSettings _appSettings;

  public MyController(IOptions<AppSettings> appSettings)
  {
     _appSettings = appSettings.Options;
  }

关于c# - 是否有内置方法来序列化数组配置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31566445/

相关文章:

c# - HttpClient GetAsync 未按预期工作

c# - 类库 COM 互操作项目的 installshield

c# - Xamarin "Aapt.exe"退出,代码为 -1073741819

c# - 在 ASP.NET Core 3 中使用 id_token

visual-studio - 将 .fsx 文件中的错误添加到 Visual Studio 错误列表中

c++ - Qt5.9.1 和 Visual Studio 2015 添加 Qt WebEngine 模块

c# - ASP.NET Core MVC 项目似乎自动添加了 AntiForgery token ?

c# - 在 ItemsControl 中绑定(bind)上下文菜单?

c# - 如何将参数传递给c#中的现有流程实例

c# - 在 Csharp winform 中将所有空字符串文本框 ("") 设置为空值的简单方法是什么?