答案 0 :(得分:1)
如果您在Formatters.JsonFormatter
中使用WebApiConfig.cs
,那么
1):如果您必须在应用程序级别忽略null值,则意味着您所有的api操作
过滤器将为
public class IgnoreNullValuesFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
actionExecutedContext.ActionContext.RequestContext.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
base.OnActionExecuted(actionExecutedContext);
}
}
并像
一样将此过滤器添加到您的WebApiConfig.cs
config.Filters.Add(new IgnoreNullValuesFilter());
在添加此过滤器后,您会发现所有api操作都会忽略空值返回数据
您无需为此添加api操作[IgnoreNullValuesFilter]
注释,因为我们在WebApiConfig.cs
中将其作为全局添加
对于点号2)和3)不要在WebApiConfig.cs
2)如果您必须使用操作过滤器忽略特定api操作的空值
然后过滤器将为
public class IgnoreNullValuesFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var objectContent = actionExecutedContext.Response.Content as ObjectContent;
if (objectContent != null)
{
var type = objectContent.ObjectType;
var value = JsonConvert.SerializeObject(objectContent.Value, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
objectContent.Value = value;
//If you want to send your response as strongly type
JObject jObject = JObject.Parse(value);
objectContent.Value = jObject;
}
base.OnActionExecuted(actionExecutedContext);
}
}
您的api可以忽略空值
[HttpGet]
[IgnoreNullValuesFilter]
public IHttpActionResult ApiName()
{
var myObject = new Item { Id = 1, Name = "Matthew", Salary = 25000, Department = null };
return Ok(myObject);
}
如果要包含空值,则只需从api中删除[IgnoreNullValuesFilter]
3)如果您不想使用任何操作过滤器,则
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public long Salary { get; set; }
public string Department { get; set; }
}
您的API将类似于
[HttpGet]
public IHttpActionResult ApiName()
{
var myObject = new Item { Id = 1, Name = "Matthew", Salary = 25000, Department = null };
return Json(myObject, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
});
}
OR
[HttpGet]
public IHttpActionResult ApiName()
{
var myObject = new Item1 { Id = 1, Name = "Matthew", Salary = 25000, Department = null };
var jsonIgnoreNullValues = JsonConvert.SerializeObject(myObject, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
JObject jObject = JObject.Parse(jsonIgnoreNullValues);
return Ok(jObject);
}
结果:
在这里您看到Item
具有属性department = null
被格式化程序忽略的情况。
您可以发送myObject
作为所需的任何类型的数据