首页 > 解决方案 > 访问我的 asp.net 核心控制台应用程序中的 appsettings.json 自定义部分

问题描述

appsettings.json我的Asp.NET 核心控制台应用程序中有以下内容:-

{
  "ConnectionStrings": {
    "ConnectionString": "Server=localhost;Database=ServiceDesk;Trusted_Connection=True"
  },
  "SP": {
    "SiteURL": "https://***.sharepoint.com/"
  }
}

现在我想访问SiteURL,我厌倦了以下但它不起作用:-

var section = config.GetSection("SP");
var ClientConfig = section.GetChildren();
string siteUrl = ClientConfig.ToString();

标签: asp.net-core.net-coreappsettings

解决方案


创建与设置匹配的模型以存储数据

public class SharePointOptions {
    public string SiteURL { get; set; }
}

然后从配置绑定到该部分

SharePointOptions options = config.GetSection("SP").Get<SharePointOptions>();
string siteUrl = options.SiteURL;

ASP.NET Core 中的参考配置

ConfigurationBinder.Get<T>绑定并返回指定的类型。ConfigurationBinder.Get<T>可能比使用更方便ConfigurationBinder.Bind


推荐阅读