当返回的对象是Castle DynamicProxy 时,我在调用信号器集线器时遇到了一些问题。
假设我在信号器集线器上有以下服务器代码(这不是真正的代码,只是为了显示问题):
public Article Read()
{
var article = new Article(0);
return article;
}
public class Article
{
public Article(int id)
{
Id = id;
}
public int Id { get; set; }
}
上述方法正确返回我的对象。如果我将此代码更改为:
public Article Read()
{
var proxyGenerator = new Castle.DynamicProxy.ProxyGenerator();
var entity = proxyGenerator.CreateClassProxy(typeof(Article), new object[]{0}, new TestInterceptor()) as Article; ;
return entity;
}
class TestInterceptor : Castle.DynamicProxy.IInterceptor
{
public void Intercept(Castle.DynamicProxy.IInvocation invocation)
{
}
}
该对象永远不会返回。客户端(javascript)没有收到任何错误,也没有执行done
任何fail
功能。
我怀疑这是序列化的问题。如果我尝试使用 Newtonsoft 序列化对象,则会收到以下错误:
System.ArgumentNullException was unhandled by user code
HResult=-2147467261
Message=Value cannot be null.
Parameter name: key
Source=mscorlib
ParamName=key
StackTrace:
at System.Collections.ObjectModel.KeyedCollection`2.Contains(TKey key)
at Newtonsoft.Json.Serialization.JsonPropertyCollection.AddProperty(JsonProperty property)
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateConstructorParameters(ConstructorInfo constructor, JsonPropertyCollection memberProperties)
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType)
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)
at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.GetContractSafe(Object value)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Type type, Formatting formatting, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Formatting formatting, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.SerializeObject(Object value)
InnerException:
有任何想法吗?这是信号器的序列化问题吗?
编辑:
感谢 Anders,我发现只有当您为其创建动态代理的类没有默认构造函数时,才会出现问题。例如public Article(int id)
. Json.NET 序列化有问题吗?