![](/img/trans.png)
[英]Serializing dates for Safari on MacOs in asp.net MVC & WebApi app with ExtJs
[英]ASP.Net WebApi is not serializing bool if set to true
我有以下模型:
public class DocumentViewModel
{
public long Id { get; set; }
public long? ParentFolderId { get; set; }
public bool IsFolder { get; set; }
public bool IsImage { get; set; }
}
以及以下API控制器:
public HttpResponseMessage GetChildren(long jobId, long folderId)
{
using (var model = DatabaseHelper.GetModel())
{
var accessLevel = MembershipHelper.GetLoggedInAccessLevel(model);
List<DocumentViewModel> documents = DocumentHelper.GetDocumentsForMobile(model, jobId, folderId, accessLevel).ToList();
return this.Request.CreateResponse(
HttpStatusCode.OK,
new { data = documents });
}
}
問題是當我在Fiddler中將它們設置為false時,在json中缺少IsFolder和IsImage的問題。 設置為true時,它們顯示良好。
我懷疑這是因為.Net認為true是默認值,並且排除了該值與默認值相同的字段。
我如何告訴.Net始終包含此值,無論如何?
在WebApiConfig
類的Register
方法(位於App_Start
文件夾中)中,嘗試添加以下行:
config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling =
Newtonsoft.Json.DefaultValueHandling.Include;
如果尚未提供默認值,這將強制Web Api包含默認值。
編輯
如果使用的Web API較舊版本沒有WebApiConfig,也可以在Global.asax.cs
的Application_Start
方法中執行此操作:
var config = GlobalConfiguration.Configuration;
var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.