【问题标题】:troubleshooting .net 5.0 modelmapper.net 5.0 模型映射器故障排除
【发布时间】:2021-05-07 16:18:54
【问题描述】:

我正在使用基于 OwinSelfHost 的 REST API 将应用程序从 .NET 4.7 移植到 net5.0(以及 ASP.Net Core)

我大部分时间都在工作,乍一看我的对象上的 CRUD 操作正在工作。但是我有其他操作在使用 POST 并且由于模型映射器无法映射属性而失败。

如果我在控制器之前拦截请求,我会得到以下结果

POST https://localhost:8189/api/SystemLanguage/UI 标头: 接受编码:gzip,放气 {"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; }
}

如果我将日志记录设置为 Trace,我可以看到这个

dbug:Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder[22] 正在尝试绑定“AUDMService.Models.IdUIExtractionParameters”类型的参数“uiParameters”... dbug:Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexObjectModelBinder[44] 尝试使用请求数据中的名称“”绑定“AUDMService.Models.IdUIExtractionParameters”类型的参数“uiParameters”... dbug: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.Nullable1[System.Guid]”类型的属性“AUDMService.Models.IdUIExtractionParameters.Id”。 dbug:Microsoft.AspNetCore.Mvc.ModelBinding.Binders.SimpleTypeModelBinder[14] 尝试绑定“System.Nullable`1[System.Guid]”类型的属性“AUDMService.Models.IdUIExtractionParameters.Id”。

我很困惑为什么......它清楚地找到了一个带有 id 的参数。我知道这不是区分大小写的,因为我有其他 POST 在他们获取 camelCase 数据时可以正常工作。我也不认为它是泛型,因为 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 终于得到了响应:在 uiParameters 中添加一个 [FromBody],它就可以很好地映射:)

【问题讨论】:

    标签: c# asp.net-core .net-5 modelmapper


    【解决方案1】:

    所以,结果证明解决方案非常简单。我的大多数控制器方法在映射模型之前使用[FromBody] 标签。仅此而已。

    【讨论】:

      猜你喜欢
      • 2013-05-31
      • 2020-05-24
      • 2011-02-28
      • 1970-01-01
      • 2020-07-16
      • 2020-07-27
      • 2019-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多