问题描述
这code:
命名空间ConsoleApplication3
{
类节目
{
静态无效的主要(字串[] args)
{
VAR的客户=新的Web客户端();
client.Headers.Add(用户代理,没有人);
VAR响应= client.DownloadString(新的URI(http://www.hanselman.com/smallestdotnet/json.ashx));
变种J = JsonConvert.DeserializeObject&其中; SmallestDotNetThing>(响应);
}
公共类SmallestDotNetThing
{
公共DotNetVersion latestVersion {获得;组; }
公开名单< DotNetVersion> allVersions {获得;组; }
公开名单< DotNetVersion> downloadableVersions {获得;组; }
}
公共类DotNetVersion
{
公众诠释各大{获得;组; }
公众诠释未成年{获得;组; }
公共字符串轮廓{获得;组; }
公众诠释?服务包{获得;组; }
公共字符串URL {获得;组; }
}
}
}
请问下使用.NET 4的.NET版本4 JSON.NET时,抛出一个异常操作可能破坏运行时的反序列化
然而,切换目标3.5(和改变JSON.NET参考3.5版本)的伟大工程。我使用的是JSON.NET从的NuGet。
思考?
似乎是在安全模式的变化在.NET 4运行时(见Karel Zikmunds回答和.NET安全博客作品)依赖于AllowPartiallyTrustedCallersAttribute程序。
卡雷尔也发布了一些选项来解决这个问题:
另外 后的StackOverflow,有可能是一个问题,协变和逆变C#
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?
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:
Another post on Stackoverflow that there might be an issue with Covariance and Contravariance in C#
这篇关于Json.NET说&QUOT;操作可能破坏运行&QUOT;在.NET 4中,而不是在.NET 3.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!