如何解决.net 5.0 模型映射器故障排除
我正在使用基于 OwinSelfHost 的 REST API 将应用程序从 .NET 4.7 移植到 net5.0(以及 ASP.Net Core)
我大部分时间都在工作,乍一看,我的对象上的 CRUD 操作正在工作。但是我还有其他操作使用 POST 并且失败,因为模型映射器无法映射属性。
如果我在控制器之前拦截请求,我会得到什么
POST https://localhost:8189/api/SystemLanguage/UI 标头: 接受编码:gzip、deflate {"id":"fdc09070-c144-4f66-a5a7-2c802ac64765"}
控制器看起来像这样
public class MyController<IdUIExtractionParameters>: ControllerBase where TUIExtraction class,IUIExtractionParameters
{
[HttpPost]
[Route("UI")]
public async Task<IActionResult> GetUi(IdUIExtractionParameters uiParameters)
{
... stripped for brevity
}
}
public class IdUIExtractionParameters
{
public Guid? Id { get; set; }
}
如果我将日志记录设置为跟踪,我可以看到这一点
dbug:Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder[22]
正在尝试绑定类型为“AUDMService.Models.IdUIExtractionParameters”的参数“uiParameters”...
调试:Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexObjectModelBinder[44]
正在尝试使用请求数据中的名称“”绑定“AUDMService.Models.IdUIExtractionParameters”类型的参数“uiParameters”...
调试:Microsoft.AspNetCore.Mvc.ModelBinding.Binders.SimpleTypeModelBinder[13]
正在尝试绑定类型为“System.Nullable1[System.Guid]' using the name 'Id' in request data ... dbug: Microsoft.AspNetCore.Mvc.ModelBinding.Binders.SimpleTypeModelBinder[15] Could not find a value in the request with name 'Id' for binding property 'AUDMService.Models.IdUIExtractionParameters.Id' of type 'System.Nullable
1[System.Guid]”的属性“AUDMService.Models.IdUIExtractionParameters.Id”。
调试:Microsoft.AspNetCore.Mvc.ModelBinding.Binders.SimpleTypeModelBinder[14]
已尝试绑定“System.Nullable`1[System.Guid]”类型的属性“AUDMService.Models.IdUIExtractionParameters.Id”。
我很困惑为什么..它清楚地找到了一个带有 id 的参数。我知道这不区分大小写,因为我有其他 POST 在获得驼峰数据时可以正常工作。我不认为这是泛型,因为 CRUD 中的 Create 也使用泛型参数来添加对象。
请注意,我使用 Newtonsoft.Json 进行 JSON 序列化/反序列化,因为我的应用程序使用了一些 System.Text.Json 中尚未包含的非常具体的内容
来自我的 Startup.cs
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter(new Newtonsoft.Json.Serialization.CamelCaseNamingStrategy()));
options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
知道为什么模型映射器没有选择 IdUIExtractionParameters.Id 吗?我对 MyController 的其他参数也有问题。常见的是保持为空的属性可以为空。
@edit:一直在尝试更多。出于测试目的,我使用了 System.Text.Json,但体验相同。我摆脱了泛型,同样的问题。使 Id 不可为空,现在我以 Guid.Empty 结束。
然后,尤里卡,我的 Google KungFu 终于产生了响应:将 [FromBody]
添加到 uiParameters
并且它映射的东西很好:)
解决方法
所以,结果证明解决方案非常简单。我的大多数控制器方法在映射模型之前使用 [FromBody]
标记。这就是全部。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。