Json.NET says “operation may destabilize the runtime” under .NET 4, but not under .NET 3.5

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-21 16:47:14

问题


This code:

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; }
        }

    }
}

Will throw an exception "operation may destabilize the runtime" on the Deserialize when using the .NET 4 version of JSON.NET under .NET 4.

However, switching the target to 3.5 (and changing the JSON.NET reference to the 3.5 version) works great. I'm using the JSON.NET from NuGet.

Thoughts?


回答1:


There seems to be a change in the Security Model in the runtime of .NET 4 (see Karel Zikmunds answer and the .NET Security Blog entry) that relies on the AllowPartiallyTrustedCallersAttribute.

Karel also posted some options to solve it:

You have these options:

  1. If you don't need APTCA, remove it.
  2. Run SecAnnotate tool from SDK and fix all transparency violations - http://blogs.msdn.com/b/shawnfa/archive/2009/11/18/using-secannotate-to-analyze-your-assemblies-for-transparency-violations-an-example.aspx.
  3. Use Level1 attribute to switch your assembly to v2 security model - http://blogs.msdn.com/b/shawnfa/archive/2009/11/11/transparency-models-a-tale-of-two-levels.aspx

Another post on Stackoverflow that there might be an issue with Covariance and Contravariance in C#



来源:https://stackoverflow.com/questions/5511171/json-net-says-operation-may-destabilize-the-runtime-under-net-4-but-not-unde

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!