Json.NET在.NET 4下说“操作可能会使运行时不稳定”,但在.NET 3.5下则不行

前端之家收集整理的这篇文章主要介绍了Json.NET在.NET 4下说“操作可能会使运行时不稳定”,但在.NET 3.5下则不行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这段代码

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new WebClient();
            client.Headers.Add("User-Agent","Nobody");
            var response = client.DownloadString(new Uri("http://www.hanselman.com/smallestdotnet/json.ashx"));

            var j = JsonConvert.DeserializeObject<SmallestDotNetThing>(response);
        }

        public class SmallestDotNetThing
        {
            public DotNetVersion latestVersion { get; set; }
            public List<DotNetVersion> allVersions { get; set; }
            public List<DotNetVersion> downloadableVersions { get; set; }
        }

        public class DotNetVersion
        {
            public int major { get; set; }
            public int minor { get; set; }
            public string profile { get; set; }
            public int? servicePack { get; set; }
            public string url { get; set; }
        }

    }
}

在.NET 4下使用.NET 4版本的JSON.NET时,将在Deserialize上抛出异常“操作可能会破坏运行时的稳定性”.

但是,将目标切换到3.5(并将JSON.NET引用更改为3.5版本)效果很好.我正在使用NuGet的JSON.NET.

思考?

解决方法

.NET 4的运行时(参见 Karel Zikmunds answer.NET Security Blog条目)中的安全模型似乎发生了变化,它依赖于AllowPartiallyTrustedCallersAttribute.

Karel还发布了一些解决方案:

You have these options:

  1. If you don’t need APTCA,remove it.
  2. Run SecAnnotate tool from SDK and fix all transparency violations –
    07002.
  3. Use Level1 attribute to switch your assembly to v2 security model –
    07003

Stackoverflow上的另一个post,C#中的协方差和逆变量可能存在问题

猜你在找的Json相关文章