JsonSerializationException on lazy loaded nHibernate object in WebApi when called from Angularjs service

放肆的年华 提交于 2020-01-12 08:24:48

问题


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

The angular 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
    };
}]);

The WebApi Get method:

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

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?

EDIT: 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;

Now I have this exception:

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?


回答1:


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

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

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



回答2:


Eager loading is worth having whole DB crash. Lazy load prevents you from loading unnecessary referenced data. But also you must ensure that you have pointed hibernate which references to load.

But your exception is thrown because of Serialization issue



来源:https://stackoverflow.com/questions/25011406/jsonserializationexception-on-lazy-loaded-nhibernate-object-in-webapi-when-calle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!