。Net Core ControllerBase操作方法JSON序列化设置
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了。Net Core ControllerBase操作方法JSON序列化设置相关的知识,希望对你有一定的参考价值。
我正在开发.Net Core 2.2 Web API。我试图利用ControllerBase方法的优势,例如AcceptedAtAction,Ok等。我已经通过Startup.cs中的.AddJsonOptions配置了JsonSerializerSettings。但是,这些操作方法似乎忽略了序列化设置。为了使这些方法符合这些设置,我还需要做其他事情吗?
Startup.cs
.AddJsonOptions(opts =>
{
opts.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
opts.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
opts.SerializerSettings.ContractResolver = new EmptyCollectionContractResolver();
})
控制器
return AcceptedAtAction(
nameof(GetPayEntryImport),
new
{
companyId = companyId,
id = timeImportResponseModel.TimeImportFileTrackingId,
version = apiVersion.ToString()
},
timeImportResponseModel);
带有空集合的响应序列化为空数组,考虑到我正在使用的ContractResolver,这不是这种情况。
{
"timeImportFileTrackingId": "bd3cd9fc-09c7-4da0-b1d9-eb8863841ed8",
"status": "The file was accepted and is currently being processed.",
"postProcessingResults": [],
"processedData": []
}
EmptyCollectionContractResolver
public class EmptyCollectionContractResolver : CamelCasePropertyNamesContractResolver
{
protected virtual JsonProperty CreateProperty(
MemberInfo member,
MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
Predicate<object> shouldSerialize = property.get_ShouldSerialize();
property.set_ShouldSerialize((Predicate<object>) (obj =>
{
if (shouldSerialize == null || shouldSerialize(obj))
return !this.IsEmptyCollection(property, obj);
return false;
}));
return property;
}
private bool IsEmptyCollection(JsonProperty property, object target)
{
object obj = property.ValueProvider.GetValue(target);
switch (obj)
{
case ICollection collection:
if (collection.Count == 0)
return true;
break;
case null:
return false;
}
if (!typeof (IEnumerable).IsAssignableFrom(property.get_PropertyType()))
return false;
PropertyInfo property1 = property.get_PropertyType().GetProperty("Count");
if (property1 == (PropertyInfo) null)
return false;
return (int) property1.GetValue(obj, (object[]) null) == 0;
}
}
答案
此问题是由我们在AddMvc扩展方法中配置OutputFormatter引起的。如果您尚未配置任何JsonOutputFormatter,则应该没问题,AddJsonOptions将提供所需的内容。否则,请确保为JsonOutputFormatter配置了所需的序列化设置。
以上是关于。Net Core ControllerBase操作方法JSON序列化设置的主要内容,如果未能解决你的问题,请参考以下文章
为什么 ASP.NET Core WebAPI 继承 ControllerBase 而不是 Controller ?