You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从appsettings配置节生成JSON字符串初始化BoxConfig

问题解决方法

错误原因

你调用configuration.GetSection("Box:ProductionConfig").ToString()得到的不是配置的JSON字符串,而是配置节对象的类型名称(比如Microsoft.Extensions.Configuration.ConfigurationSection),所以Newtonsoft.Json解析时会遇到非JSON格式的字符,抛出解析错误。

解决方案

方法一:将配置节序列化为JSON字符串

使用Newtonsoft.Json把配置节内容序列化为标准JSON字符串,再传给BoxConfigBuilder.CreateFromJsonString():

this.token = token;
// 获取配置节并转换为JObject
var productionConfig = configuration.GetSection("Box:ProductionConfig").Get<Newtonsoft.Json.Linq.JObject>();
// 序列化为JSON字符串
var configJson = productionConfig.ToString();
// 构建Box配置
var config = BoxConfigBuilder.CreateFromJsonString(configJson).Build();
_session = new BoxJWTAuth(config);

方法二:直接绑定到强类型对象(可选)

如果不想处理JSON序列化,可以定义一个和Box配置结构匹配的类,直接绑定后构建配置:

  1. 定义配置类:
public class BoxAppSettings
{
    public string ClientID { get; set; }
    public string ClientSecret { get; set; }
    public AppAuthSettings AppAuth { get; set; }
}

public class AppAuthSettings
{
    public string PublicKeyID { get; set; }
    public string PrivateKey { get; set; }
    public string Passphrase { get; set; }
}

public class BoxProductionConfig
{
    public BoxAppSettings BoxAppSettings { get; set; }
    public string EnterpriseID { get; set; }
}
  1. 绑定并构建配置:
this.token = token;
var productionConfig = new BoxProductionConfig();
configuration.GetSection("Box:ProductionConfig").Bind(productionConfig);
// 手动构建BoxConfig
var config = new BoxConfigBuilder()
    .SetClientId(productionConfig.BoxAppSettings.ClientID)
    .SetClientSecret(productionConfig.BoxAppSettings.ClientSecret)
    .SetPublicKeyId(productionConfig.BoxAppSettings.AppAuth.PublicKeyID)
    .SetPrivateKey(productionConfig.BoxAppSettings.AppAuth.PrivateKey)
    .SetPassphrase(productionConfig.BoxAppSettings.AppAuth.Passphrase)
    .SetEnterpriseId(productionConfig.EnterpriseID)
    .Build();
_session = new BoxJWTAuth(config);

额外注意事项

你提供的appsettings.json中存在中文引号(“”),需要全部替换为英文引号(""),否则.NET配置系统无法正确读取配置内容。修正后的示例:

{
  "Box": {
    "ProductionConfig": {
      "boxAppSettings": {
        "clientID": "dsafafdsafasdfasdfasdfasdfsadfsdaf",
        "clientSecret": "dfasdfasdfasdfasdfdsfdfedfdf",
        "appAuth": {
          "publicKeyID": "kdjfkalsfjakslf;a",
          "privateKey": "-----BEGIN ENCRYPTED PRIVATE KEY-----\nkdsajfl;sajdkfl;asjdkfl;sajdkfl;asjkdfl;asjdkfl;asjfklas;djfkdasld;fjklsa;fjskal;f\n-----END ENCRYPTED PRIVATE KEY-----\n",
          "passphrase": "dasfsafsadfasdfasdfasdfsa"
        }
      },
      "enterpriseID": "dsafasfdsafasdf"
    },
    "ProductionDomain": "https://testing.app.box.com"
  }
}

内容的提问来源于stack exchange,提问作者Qiuzman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 23:31:21