Web API转换为Azure移动服务未对所有属性进行序列化 [英] Web API converted to Azure Mobile Service not serializing all properties

查看:90
本文介绍了Web API转换为Azure移动服务未对所有属性进行序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有效的Web API,正在将其转换为.Net Azure移动服务. API返回复杂的模型-具有属性的对象-其中一些是其他对象的集合.可以使用普通的Web API达到预期效果,但是使用Azure移动服务时,我遇到了一个问题,即我的模型之一没有将其所有属性序列化.

I have a working Web API that i am converting to a .Net Azure Mobile Service. The API returns a complex model - objects with properties - some of which are collections of other objects. This works as expected with plain Web API but with Azure Mobile Services I have an issue where one of my models does not have all it's properties serialized.

当我在控制器的return语句上设置断点时,我看到所有属性及其值都存在.这使我相信问题出在序列化(JSON).

When i set a break point on the return statement in the controller, I see that all the properties and their values are present. This leads me to believe that the issue is with serialization (JSON).

return Request.CreateResponse(HttpStatusCode.OK, myModel);

要序列化的属性的示例:

Examples of properties that are being serialized:

public Guid Id { get; set; }
public IEntityDto ModelDto { get; set; } //this is an object with many properties all of which serialize

未序列化的属性示例:

public ItemStatus Status { get; set; }  //this is an enum
public string Message { get; set; }
public string TestProp { get; set; } //this is a simple string property I added to help debug

如何进行进一步调试,以便了解为什么排除了这些属性?

How can I go about further debugging this so that i can see why these properties are being excluded?

注意:目前,我仍在本地运行此功能,而不是在Azure上运行.这是与Visual Studio 2013 Update 2 RTM一起使用的.

Note: At the moment I am still running this locally not off Azure. This is with Visual Studio 2013 Update 2 RTM.

更新:经过仔细检查,似乎未序列化的属性是枚举或值为null的属性.

UPDATE: Upon closer inspection it appears that the properties not being serialized are properties that are either enums or have a value of null.

推荐答案

正如@carlosfigueira在对原始问题的评论中提到的那样,JSON序列化程序的默认行为是排除具有null和默认值的属性.为了解决这个问题,我更改了以下设置:

As @carlosfigueira mentioned in a comment to the original question, the default behavior of the JSON serializer is to exclude properties with null and default values. To address this I changed the following settings:

  httpConfig.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include;
  httpConfig.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;

...,其中httpConfigHttpConfiguration类型.您可以在应用启动时进行这些更改-在WebApiConfig.cs之类的配置文件中,也可以直接在Global.asax.cs中进行.

...where httpConfig is of type HttpConfiguration. You can make these changes on app start - in a config file like WebApiConfig.cs or directly in Global.asax.cs.

这篇关于Web API转换为Azure移动服务未对所有属性进行序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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