无法序列化响应正文内容类型 [英] Failed to serialize the response body for content type

查看:451
本文介绍了无法序列化响应正文内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建一个使用两个控制器和一个ApiControllers应用MVC4。我修改了默认的Web API路线包括操作名称。当我试图让基准的名单,我收到此错误消息:


  

在'ObjectContent`1类型没有序列化反应机构
  内容类型应用/ JSON的;字符集= UTF-8


设置InnerException是这样的(我在这种情况下返回JSON,同样使用XML发生):

 的InnerException:{
消息:发生了错误。
ExceptionMessage:错误获取从NHibernate.Proxy.DefaultLazyInitializer'IdentityEqualityComparer的价值。
ExceptionType:Newtonsoft.Json.JsonSerializationException,
堆栈跟踪:在Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(对象目标)在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter作家,对象的值,JsonObjectContract合同,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)在Newtonsoft .Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter作家,对象的值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeISerializable(JsonWriter作家,ISerializable的价值,JsonISerializableContract合同,JsonProperty成员, JsonContainerContract collectionContract,JsonProperty containerProperty)在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter作家,对象的值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter作家,对象值,JsonObjectContract合同,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter作家,对象的值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)在Newtonsoft.Json.Serialization。 JsonSerializerInternalWriter.SerializeList(JsonWriter作家,IWrappedCollection值,JsonArrayContract合同,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter作家,对象的值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty )在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(jsonWriter jsonWriter,对象值)Newtonsoft.Json.JsonSerializer.SerializeInternal(jsonWriter jsonWriter,对象值) System.Net.Http.Formatting.JsonMediaTypeFormatter.<>c__DisplayClassd.<WriteToStreamAsync>b__c()在System.Threading.Tasks.TaskHelpers.RunSynchronously(动作的动作,令牌的CancellationToken),
的InnerException:{
消息:发生了错误。
ExceptionMessage:通用语言运行时检测到无效的程序。
ExceptionType:System.InvalidProgramException,
堆栈跟踪:在GetIdentityEqualityComparer(对象)在Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(对象目标)
}

这是code,我运行:

  //获取API /基准/ getincomplete
        [HTTPGET]
        公众的IList&LT;&基准GT; GetIncomplete()
        {
            变种S = HibernateModule.CurrentSession;
            VAR benchList = s.QueryOver&LT;&基准GT;()
                                。凡(B = GT;!b.Completed)
                                。凡(B = GT;!b.Deleted)
                                .OrderBy(B = GT; b.Id).ASC
                                .LIST&LT;&基准GT;();            返回benchList;
        }

这是基准模型:

 公共类基准测试
    {
        公共虚拟INT标识{搞定;组; }
        [需要]
        [数据类型(DataType.Date)
        公共虚拟的DateTime日期{搞定;组; }
        [必需的,ScriptIgnore]
        公共虚拟的IList&LT;&的TestResult GT;结果{搞定;组; }
        [需要]
        公共虚拟的IList&LT;&TestCase的GT; {的TestCase获得;组; }
        [AllowHtml]
        公共虚拟字符串描述{搞定;组; }
        公共虚拟设备设备{搞定;组; }
        公共虚拟BOOL发布{搞定;组; }
        [显示(名称=删除),ScriptIgnore]
        公共虚拟BOOL删除{搞定;组; }
        公共虚拟BOOL完成{搞定;组; }        公共标准()
        {
            结果=新的List&LT;&的TestResult GT;();
            的TestCase =新的List&LT;&TestCase的GT;();
            发布时间= FALSE;
            删除= FALSE;
            完成= FALSE;
        }
    }

我不是很确定问题所在。难道是NHibernate的代理(我用流利NHibernate的)?奇怪的是,如果我不使用ApiController,并手动返回JSON,这工作得很好!

更新:

按下面的答案,这是code,我不得不在的Application_Start()地址:

  HttpConfiguration配置= GlobalConfiguration.Configuration;
((DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = TRUE;


解决方案

的<一个href=\"https://github.com/nhibernate/nhibernate-core/blob/master/src/NHibernate/IdentityEqualityComparer.cs\"><$c$c>IdentityEqualityCompairer在NHibernate的框架似乎有 [SerializableAttribute] 注释。

从评论上采取一个答案这里的 href=\"http://stackoverflow.com/questions/12843972/why-wont-web-api-deserialize-this-but-json-net-will\">Why不会的Web API反序列化这一点,但JSON.Net会?它看起来像JSON.NET配置有点不同的WebAPI使用之间,它的单机使用。


  

Json.NET串行器默认设置IgnoreSerializableAttribute为true。在的WebAPI,我们设置为false。


所以,给你不能拿 [SerializableAttribute] 关闭(因为它不是你的code内),您可以尝试更改默认的WebAPI JSON.NET设置使用这个答案<一个忽略它href=\"http://stackoverflow.com/questions/13263988/asp-net-web-api-and-serializable-class\">here:

<$p$p><$c$c>((DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = TRUE;

也许还考虑的使用DTO你的结果在响应发送过 - 这将让您对通过线路发送的对象完全控制

I'm building a MVC4 application that uses both Controllers and ApiControllers. I modified the default Web API route to include action names. When I try to get a list of Benchmarks, I'm getting this error message:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'

The InnerException is this (I'm returning JSON in that case, same happens with XML):

"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Error getting value from 'IdentityEqualityComparer' on 'NHibernate.Proxy.DefaultLazyInitializer'.",
"ExceptionType": "Newtonsoft.Json.JsonSerializationException",
"StackTrace": " at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value) at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value) at System.Net.Http.Formatting.JsonMediaTypeFormatter.<>c__DisplayClassd.<WriteToStreamAsync>b__c() at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)",
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Common Language Runtime detected an invalid program.",
"ExceptionType": "System.InvalidProgramException",
"StackTrace": " at GetIdentityEqualityComparer(Object ) at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
}

This is the code that I run:

// GET api/benchmark/getincomplete
        [HttpGet]
        public IList<Benchmark> GetIncomplete()
        {
            var s = HibernateModule.CurrentSession;
            var benchList = s.QueryOver<Benchmark>()
                                .Where(b => !b.Completed)
                                .Where(b => !b.Deleted)
                                .OrderBy(b => b.Id).Asc
                                .List<Benchmark>();

            return benchList;
        }

And this is the Benchmark model:

public class Benchmark
    {
        public virtual int Id { get; set; }
        [Required]
        [DataType(DataType.Date)]
        public virtual DateTime Date { get; set; }
        [Required, ScriptIgnore]
        public virtual IList<TestResult> Results { get; set; }
        [Required]
        public virtual IList<TestCase> TestCases { get; set; }
        [AllowHtml]
        public virtual string Description { get; set; }
        public virtual Device Device { get; set; }        
        public virtual bool Published { get; set; }
        [Display(Name = "Deleted"), ScriptIgnore]
        public virtual bool Deleted { get; set; }
        public virtual bool Completed { get; set; }

        public Benchmark() 
        {
            Results = new List<TestResult>();
            TestCases = new List<TestCase>();
            Published = false;
            Deleted = false;
            Completed = false;
        }
    }

I'm not quite sure where the problem lies. Could it be the NHibernate Proxy (I use Fluent NHibernate)? The odd thing is that if I don't use an ApiController, and manually return JSON, this works just perfectly!

Update:

As per the answer below, this is the code I had to add in Application_Start() :

HttpConfiguration config = GlobalConfiguration.Configuration;
((DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;

解决方案

The IdentityEqualityCompairer in the NHibernate framework appears to have the [SerializableAttribute] annotation.

Taken from a comment on an answer here Why won't Web API deserialize this but JSON.Net will? it looks like JSON.NET is configured a little differently between WebApi usage and it's standalone usage.

Json.NET serializer by default set the IgnoreSerializableAttribute to true. In WebAPI, we set that to false.

So given you cannot take the [SerializableAttribute] off (as it is not within your code) you could try changing the default WebApi JSON.NET setting to ignore it using this answer here:

((DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;

Perhaps also consider Using a DTO for your results being sent over in the response - this will give you full control over the object being sent over the wire.

这篇关于无法序列化响应正文内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆