c# - 升级到 3.1 c# 时请求实体为 Null
问题描述
已编辑
我刚来这地方。所以如果这是一个重复的问题,请原谅我。
当我们从 2.0 迁移到 dotnet core 3.1 时遇到问题。解释如下:
首先我们的实体是这样的
class Student {
string StudentId
}
所以当我们像这样使用我们的控制器时
public async Task<IActionResult> GetStudentByIdAsync([FromBody] Student studentrequest)
如果我们将实体发送为
或,我们在2.0中从未得到Studentrequest
null{"studentId":1}
{"studentId":"1"}
两者都工作得很好。
但是在3.1中,如果我们将请求 作为{"studentId":1}
. 我们的 UI 基于这种格式,它是一个独立的外部团队。基于此,我们有很多工作。所以他们和我们都不愿意改变。
还有一点,之前我们用addMvc()
in Startup.cs
,现在我们用addControllers()
. 这可能是造成这种情况的原因吗?
任何人都可以帮忙吗?提前致谢。
解决方案
感谢戴的评论:
您使用的是什么 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);
希望这对其他人有帮助。
推荐阅读
- asp.net-core - Automapper:“缺少类型映射配置或不支持的映射。”
- python - 按条件检索时间行。让代码在一天内工作
- python-3.x - Picamera http流叠加静态图片
- macos - AppKit 如何决定是否将窗口的标题和工具栏呈现为灰色,这是可配置的吗?
- css - 为什么 CSS text-align:center; 不行?
- arduino - 测试 Arduino WiFiServer 消息
- xamarin - 如何使用 xamarin.forms pcl 或将其转换为 xamarin native
- python - 根据xml标签标题获取文本
- java - 是否可以在 Azure Functions 的 TimerTrigger 中调用 rest api
- c# - 浏览器历史记录/缓存通过 c# 代码清理