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

我正在构建一个使用控制器和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将您的结果发送到响应中 – 这将使您完全控制通过电线发送的对象.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....