加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

休息 – 无法序列化内容类型的响应正文

发布时间:2020-12-15 23:30:57 所属栏目:asp.Net 来源:网络整理
导读:我正在构建一个使用控制器和ApiControllers的MVC4应用程序.我修改了默认的Web API路由以包含动作名称.当我尝试获得基准列表时,我收到此错误消息: The ‘ObjectContent`1’ type failed to serialize the response body for content type ‘application/json
我正在构建一个使用控制器和ApiControllers的MVC4应用程序.我修改了默认的Web API路由以包含动作名称.当我尝试获得基准列表时,我收到此错误消息:

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

InnerException是这样的(我在这种情况下返回JSON,与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,JsonContract valueContract,JsonContainerContract containerContract,JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeISerializable(JsonWriter writer,ISerializable value,JsonISerializableContract contract,JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer,JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer,IWrappedCollection values,JsonArrayContract contract,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)"
}

这是我运行的代码:

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

这是基准模型:

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

我不太清楚问题所在.可能是NHibernate Proxy(我使用Fluent NHibernate)吗?奇怪的是,如果我不使用ApiController,并手动返回JSON,这很好用!

更新:

根据下面的答案,这是我在Application_Start()中添加的代码:

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

解决方法

NHibernate框架中的 IdentityEqualityCompairer似乎有[SerializableAttribute]注释.

从对这个答案的评论来看,Why won’t Web API deserialize this but JSON.Net will?看起来,JSON.NET在WebApi使用和独立使用之间配置有所不同.

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

因此,由于您无法使用[SerializableAttribute](因为它不在代码中),您可以尝试更改默认的WebApi JSON.NET设置,以忽略它使用此答案here:

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

也可以考虑使用DTO将您的结果发送到响应中 – 这将使您完全控制通过电线发送的对象.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读