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

前端之家收集整理的这篇文章主要介绍了休息 – 无法序列化内容类型的响应正文前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在构建一个使用控制器和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将您的结果发送到响应中 – 这将使您完全控制通过电线发送的对象.

原文链接:https://www.f2er.com/aspnet/250475.html

猜你在找的asp.Net相关文章