c# - .Net Core ControllerBase Action Method JSON 序列化设置

标签 c# asp.net-core asp.net-core-webapi

我正在开发 .Net Core 2.2 Web API。我正在尝试利用 ControllerBase 方法,例如 AcceptedAtAction、Ok 等。我已经通过我的 Startup.cs 中的 .AddJsonOptions 配置了我的 JsonSerializerSettings。但是,这些操作方法似乎忽略了序列化设置。为了让这些方法遵循这些设置,我还需要做些什么吗?

启动.cs

.AddJsonOptions(opts =>
  {
    opts.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
    opts.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    opts.SerializerSettings.ContractResolver = new EmptyCollectionContractResolver();
  })

Controller

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 引起的。如果你没有配置任何 JsonOutputFormatters,你应该没问题,AddJsonOptions 会提供你需要的。否则,请确保为 JsonOutputFormatter 配置了所需的序列化设置。

关于c# - .Net Core ControllerBase Action Method JSON 序列化设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59073337/

相关文章:

c# - 通过执行的应用程序关闭执行程序应用程序

c# - 为什么 web.config 是在发布时创建的,而不是在 Asp.Net Core API 中构建项目时创建的?

c# - 在 ASP.NET 5 中找不到 CSS 文件

authentication - 检查用户是否存在于 ASP.NET Core WebAPI JWT 身份验证中

asp.net - NLog 在 VS 2017 .NET Core 项目中不起作用

c# - 在当前打开的应用程序顶部显示隐藏的窗口窗体

c# - MVC 构建电子邮件正文

C# 遍历两个列表 - 可交换的内/外循环

reactjs - 如何在 ASP.NET Core 3 React 应用程序的 index.html 中从服务器注入(inject)数据

c# - 在 Web API 中上传单个文件