首页 > 解决方案 > 升级到 3.1 c# 时请求实体为 Null

问题描述

已编辑

我刚来这地方。所以如果这是一个重复的问题,请原谅我。

当我们从 2.0 迁移到 dotnet core 3.1 时遇到问题。解释如下:

首先我们的实体是这样的

class Student {
      string StudentId 
}

所以当我们像这样使用我们的控制器时

 public async Task<IActionResult> GetStudentByIdAsync([FromBody] Student studentrequest)

如果我们将实体发送为 或,我们在2.0中从未得到Studentrequestnull{"studentId":1}{"studentId":"1"}

两者都工作得很好。

但是在3.1中,如果我们将请求 作为{"studentId":1}. 我们的 UI 基于这种格式,它是一个独立的外部团队。基于此,我们有很多工作。所以他们和我们都不愿意改变。

还有一点,之前我们用addMvc()in Startup.cs,现在我们用addControllers(). 这可能是造成这种情况的原因吗?

任何人都可以帮忙吗?提前致谢。

标签: c#asp.net-coremicroservicesasp.net-core-3.1

解决方案


感谢戴的评论:

您使用的是什么 JSON 反序列化库?ASP.NET Core 3+ 使用 Microsoft 的新 JSON 库而不是 Newtonsoft.Json - 我怀疑它拒绝将 camelCase studentId JSON 属性与您的 PascalCase StudentId 类成员匹配。——

我能够理解这是从作为 dotnet Core 2.0 中的格式化程序的 NewtonSoft.Json 到 3.X 中的 System.Text.Json 的实现的变化。

在寻找解决方案后,我在媒体上找到了这篇文章。

防止我的错误的解决方案是将Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget 添加到您的解决方案中,并在您的 startup.cs 配置方法中集成以下或类似的行:

        _ = services.AddControllers(options =>
          {
              options.Filters.Add(typeof(WithHeaderHandlerAttribute));
          })
           .AddNewtonsoftJson(
            options =>
            options.SerializerSettings.ContractResolver = new
            CamelCasePropertyNamesContractResolver()).AddJsonOptions(options => options.JsonSerializerOptions.PropertyNameCaseInsensitive = true);

希望这对其他人有帮助。


推荐阅读