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

调用Twilio AccessToken.ToJwt()抛出cty重复键异常的原因

问题场景

使用Twilio Conversation服务生成JWT令牌时,调用new Twilio.Jwt.AccessToken(/*parameters*/).ToJwt()方法抛出以下异常:

'token.ToJwt()' threw an exception of type 'System.ArgumentException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2147024809
    HelpLink: null
    InnerException: null
    Message: "An item with the same key has already been added. Key: cty"
    ParamName: null
    Source: "System.Private.CoreLib"
    StackTrace: "   at System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException[T](T key)\r\n   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)\r\n   at Twilio.Jwt.BaseJwt.ToJwt()"
    TargetSite: {Void ThrowAddingDuplicateWithKeyArgumentException[T](T)}
异常根因

这个问题和传入的构造参数没有关系,是Twilio .NET SDK特定版本的内置bug:

  • JWT生成过程中,SDK内部用字典结构存储JWT头的键值对,cty(内容类型)是JWT标准规定的头字段
  • 出问题的SDK版本中,cty键会被重复写入两次:第一次是BaseJwt基类初始化JWT头时默认添加,第二次是AccessToken子类添加Conversation服务授权Grant时,又重复追加了一次同名的cty键
  • .NET的Dictionary不允许插入重复键,直接抛出ArgumentException,也就是你看到的重复键错误。
修复方案
  • 直接把项目里引用的Twilio NuGet包升级到最新稳定版即可解决
  • 如果因为依赖限制不能升级最新版,可以回退到没有该bug的旧版本(比如5.5.0)
  • 不需要调整生成AccessToken时传入的账号密钥、身份标识等业务参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 12:19:52