调用Azure DevOps API时System.Security.Permissions加载异常求助
解决Azure DevOps API反序列化SecurityNamespaceDescription时的程序集加载异常
方案1:自定义DTO类(推荐)
直接复用Microsoft.TeamFoundation.Framework.Client中的SecurityNamespaceDescription类型会引入不必要的程序集依赖问题,最佳做法是根据API返回的JSON结构自定义DTO类,完全脱离对微软内置类型的依赖:
namespace azdosupport.TFSresponseModels { public class SecurityNamespaceDescriptionRoot { public SecurityNamespaceDescriptionDto[] value { get; set; } public int count { get; set; } } public class SecurityNamespaceDescriptionDto { // 对照Azure DevOps API返回的字段逐一定义,示例字段如下: public Guid NamespaceId { get; set; } public string Name { get; set; } public string DisplayName { get; set; } public int Flags { get; set; } public string ElementLength { get; set; } // 其他字段根据实际API响应补充 } }
修改反序列化代码为:
SecurityNamespaceDescriptionRoot infoblock = JsonConvert.DeserializeObject<SecurityNamespaceDescriptionRoot>(ResponseBody);
这种方式彻底避免了对System.Security.Permissions的依赖,从根源解决版本冲突问题。
方案2:添加程序集绑定重定向
如果必须使用微软内置的SecurityNamespaceDescription类型,可以通过程序集绑定重定向,将请求的0.0.0.0版本指向已安装的8.0.0.0版本。在项目的app.config(桌面应用)或web.config(Web应用)中添加以下配置:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Security.Permissions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
方案3:检查并对齐项目框架与NuGet包版本
确认项目的目标框架版本与System.Security.Permissions NuGet包版本兼容:
- 若使用.NET 6+,确保已安装最新稳定版的
System.Security.PermissionsNuGet包 - 移除项目中对
System.Security.Permissions的系统程序集引用,仅保留NuGet包引用 - 清理项目的
bin和obj目录,重新编译
问题原因解析
异常的核心是Microsoft.TeamFoundation.Framework.Client中的SecurityNamespaceDescription类型内部依赖了System.Security.Permissions组件,Newtonsoft.Json在反序列化反射该类型时,尝试加载版本号为0.0.0.0的程序集(这个版本实际不存在),导致文件找不到错误。而PowerShell使用动态泛型对象,不需要反射具体的强类型,因此不会触发该问题。
内容的提问来源于stack exchange,提问作者Jeff Gedney
相关产品推荐
相关产品推荐

