Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

json.net

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?

like image 284
Scott Hanselman Avatar asked Apr 01 '11 08:04

Scott Hanselman


1 Answers

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#

like image 155
Jehof Avatar answered Nov 15 '22 18:11

Jehof