从Angularjs服务调用时WebApi中的延迟加载的nHibernate对象上的JsonSerializationException [英] JsonSerializationException on lazy loaded nHibernate object in WebApi when called from Angularjs service

查看:173
本文介绍了从Angularjs服务调用时WebApi中的延迟加载的nHibernate对象上的JsonSerializationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从Angularjs服务中调用WebApi控制器的Get方法.

I am calling a WebApi controller Get method from an Angularjs service.

角度服务:

app.service('MyService', ['$http', function ($http) {

    var getMyObjects = function () {
        var myObjects;
        var promise = $http.get('/api/objects/').success(function (data) {
            myObjects = data;
         }).error(function (data, status, headers, config) {

         });

         return promise;
    };

    return {
        myObjects: myObjects
    };
}]);

WebApi Get方法:

The WebApi Get method:

public class ObjectsController : ApiController
{
    public IEnumerable<MyObject> Get()
    {
        return _objectRepository.GetAll().ToArray();
    }
}

我在客户端上得到一个500 server error,其内部异常是:

I am getting a 500 server error on the client, the inner exception of which is:

ExceptionMessage: "Error getting value from 'IdentityEqualityComparer' on 
'NHibernate.Proxy.DefaultLazyInitializer'."
ExceptionType: "Newtonsoft.Json.JsonSerializationException"

我应该怎么做才能解决此问题?

What should I do to resolve this issue?

我根据此答案通过在WebApiConfig.cs中添加以下一个衬纸来解决上述异常:

I resolved the above exception by adding the following one liner to WebApiConfig.cs as per this answer:

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

现在我有这个例外:

ExceptionMessage: "Error getting value from 'DefaultValue'
on 'NHibernate.Type.DateTimeOffsetType'."
ExceptionType: "Newtonsoft.Json.JsonSerializationException"

有什么想法可以解决这个问题吗?

Any ideas on if there is something similar I can do to fix this?

推荐答案

基于此答案

Based on this answer and this answer, I have fixed the issue by adding the following class

public class NHibernateContractResolver : DefaultContractResolver
{
   protected override JsonContract CreateContract(Type objectType) 
   {
      if (typeof(NHibernate.Proxy.INHibernateProxy).IsAssignableFrom(objectType))
          return base.CreateContract(objectType.BaseType);

        return base.CreateContract(objectType);
    }
}

,然后将其设置为Global.asax.csApplication_Start中的合同解析器:

and then setting it as the contract resolver in Application_Start in Global.asax.cs:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
                            .ContractResolver = new NHibernateContractResolver();

这篇关于从Angularjs服务调用时WebApi中的延迟加载的nHibernate对象上的JsonSerializationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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