JsonMediaTypeFormatter尝试使用IgnoreDataMember属性反序列化属性

时间:2015-05-11 08:53:38

标签: json deserialization asp.net-web-api circular-reference

我有一个JSON字符串,例如:

{
  "$id": "1",
  "Username": "mrdan",
  "Email": "mrdan@hotmale.co.uk",
  "Roles": [
    {
      "$id": "2",
      "Name": "Super Admin",
      "Users": [
        {
          "$ref": "1"
        }
      ],
      "Permissions": [
        {
          "$id": "3",
          "Name": "UserSave",
          "Roles": [
            {
              "$ref": "2"
            }
          ],
          "Id": "2d9a1268-6e53-4749-89f6-59ec0132e737"
        },
        {
          "$id": "4",
          "Name": "UserView",
          "Roles": [
            {
              "$ref": "2"
            },
            {
              "$id": "5",
              "Name": "Call Centre Manager",
              "Users": [
                {
                  "$id": "6",
                  "Username": "mrdan2",
                  "Email": "mrdan2@hotmale.co.uk",
                  "Roles": [
                    {
                      "$ref": "5"
                    }
                  ],
                  "Id": "579a0c65-26f6-4be5-aa78-72e1cd76ba11"
                }
              ],
              "Permissions": [
                {
                  "$ref": "4"
                }
              ],
              "Id": "f44702ef-03b0-4694-afcf-dc79c6826938"
            }
          ],
          "Id": "69c9a26b-0524-4b71-9675-5f167d2a9afc"
        },
        {
          "$id": "7",
          "Name": "UserDelete",
          "Roles": [
            {
              "$ref": "2"
            }
          ],
          "Id": "f4310d1e-1888-4917-a1de-e3f63f77a88a"
        }
      ],
      "Id": "c5f10adc-1d46-424e-afab-584cc0a8375c"
    }
  ],
  "Id": "45fa847e-ceae-4fbb-b1cc-a42dfeb53c72"
}

...我想发送给WebAPI操作。 JSON是我在用一个多汁的循环引用加载用户后获得的,我有:

config.Formatters.Add(
    new JsonMediaTypeFormatter()
    {
         SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings()
         {
              PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects,
              ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize
         }
    }
);

...在我的初创公司中用于WebAPI,这在下到客户端的过程中运行良好。 (我还没有对客户端进行测试,我现在正在使用RESTClient for Firefox进行测试。)

现在,我遇到的问题是当我将数据发送回服务器时。我的控制器功能是:

[Route("api/User")]
[HttpPost]
[OperationBehavior(TransactionScopeRequired = true)]
public User Save([FromBody]User user)

现在,当我发送一个没有任何循环引用的用户时,一切正常,当我发送任何没有循环引用的东西时,它都能正常工作。

症状是它在反序列化时挂起。我已经测试过一个自定义的httphandler能够将它从json字符串反序列化为一个User对象,并且所有的循环引用都是完整的,所以为什么它不能为我的动作做呢?

如果您需要更多信息,请告诉我,这实在令我感到沮丧,因为我无法调试它:(

修改

我将这样的POCO反序列化:

[DataContract]
public class User : ServerEntityBase<User>
{
    [DataMember]
    public string Username { get; set; }
    [DataMember]
    public string Email { get; set; }
    [DataMember]
    [Associated]
    public ICollection<Role> Roles { get; set; }

    [IgnoreDataMember]
    public string PasswordHash { get; set; }

    [IgnoreDataMember]
    public override Expression<Func<IUpdateConfiguration<User>, object>> SavingObjectGraph
    {
        get
        {
            return map => map.AssociatedCollection(u => u.Roles);
        }
    }

}

在反序列化过程中,奇怪的是实际调用了Get的SaveObjectGraph属性。我不知道该怎么称呼它,我不喜欢它。在调试过程中,如果我跳过Get调用,它实际上已成功反序列化,并以User作为参数输入我的Save操作。

我有什么想法可以停止对Get的调用吗?更好的是,是什么导致它被称为开始?

编辑2

这里是堆栈跟踪的最高部分,当Get被调用时,现在的问题是如何忽略来自&#34;元数据提供程序&#34; :)去那儿!

   at UKStainedGlass.Business.Entities.User.get_SavingObjectGraph()
   at GetSavingObjectGraphFromUser(Object )
   at System.Web.Http.Metadata.Providers.AssociatedMetadataProvider`1.<>c__DisplayClass3.<GetMetadataForPropertiesImpl>b__0()
   at System.Web.Http.Metadata.ModelMetadata.get_Model()
   at System.Web.Http.Validation.DefaultBodyModelValidator.ValidateNodeAndChildren(ModelMetadata metadata, ValidationContext validationContext, Object container, IEnumerable`1 validators)
   at System.Web.Http.Validation.DefaultBodyModelValidator.ValidateProperties(ModelMetadata metadata, ValidationContext validationContext)
   at System.Web.Http.Validation.DefaultBodyModelValidator.ValidateNodeAndChildren(ModelMetadata metadata, ValidationContext validationContext, Object container, IEnumerable`1 validators)
   at System.Web.Http.Validation.DefaultBodyModelValidator.Validate(Object model, Type type, ModelMetadataProvider metadataProvider, HttpActionContext actionContext, String keyPrefix)
   at System.Web.Http.ModelBinding.FormatterParameterBinding.<ExecuteBindingAsyncCore>d__0.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
   at System.Web.Http.ModelBinding.FormatterParameterBinding.ExecuteBindingAsyncCore(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, HttpParameterDescriptor paramFromBody, Type type, HttpRequestMessage request, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
   at System.Web.Http.ModelBinding.FormatterParameterBinding.ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
   at System.Web.Http.Controllers.HttpActionBinding.<ExecuteBindingAsyncCore>d__0.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
   at System.Web.Http.Controllers.HttpActionBinding.ExecuteBindingAsyncCore(HttpActionContext actionContext, CancellationToken cancellationToken)
   at System.Web.Http.Controllers.HttpActionBinding.ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()

1 个答案:

答案 0 :(得分:0)

好吧我终于解决了这个问题!

结果显示堆栈跟踪中的线索。 WebAPI中存在用于模型绑定的验证过程,在该过程中的某个位置调用了名为ShouldValidateType(Type type)的内容。该函数对我的SavingObjectGraph属性返回true,这反过来又导致User to Role to User等的无限循环。

我必须改变两个地方来排序,首先关闭,class DefaultBodyModelValidator的子类,覆盖它的函数public override bool ShouldValidateType(Type type),在查看我的SavingObjectGraph属性时返回false。像这样:

public class CustomBodyModelValidator : DefaultBodyModelValidator
{
    public override bool ShouldValidateType(Type type)
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Expression<>))
        {
            return false;
        }
        return base.ShouldValidateType(type);
    }
}

然后,在我的WebAPI服务上注册,如下所示:

    public void Configuration(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host. 
        HttpConfiguration config = new HttpConfiguration();
        Register(config);

        config.Services.Replace(typeof(IBodyModelValidator), new CustomBodyModelValidator());

        appBuilder.UseWebApi(config);
    }

问题解决了!我已经忘记了我在哪里找到答案我害怕:(但事实证明阅读堆栈痕迹可以提供帮助;)