【问题标题】:ASP.NET Core Web API Model binding behavior changeASP.NET Core Web API 模型绑定行为更改
【发布时间】:2020-02-26 03:40:43
【问题描述】:

我有一个带有自定义模型类型的简单控制器标题 - 没有无参数构造函数和公共设置器

我在 asp.net mvc core 2.2 和 3.1 中尝试了以下代码。

模型类:

public class Heading
{
    public string Title { get; }
    public Heading(string title)
    {
        Title = title;
    }
}

API 控制器:

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    [HttpPost]
    public void Post([FromBody] Heading value)
    {
    }
}

使用 .net core 2.2,绑定可以完美运行。但是对于core 3.1,它会抛出错误

System.NotSupportedException:引用类型的反序列化 不支持没有无参数构造函数。类型 'WebApplication3.Controllers.Heading' 在 System.Text.Json.ThrowHelper.ThrowNotSupportedException_DeserializeCreateObjectDelegateIsNull(类型 无效类型)

这是行为上的改变吗?还能实现吗?

【问题讨论】:

  • 我很惊讶 .net core 2.2 实际上支持没有无参数构造函数的模型。它是如何工作的?

标签: c# asp.net-core asp.net-core-3.0


【解决方案1】:

ASP.NET Core 2.2 中,它之所以有效,是因为 Newtonsoft.Json。在 ASP.NET Core 版本 >= 3.0 中,它被 System.Text.Json 取代。 Here 更多关于 System.Text.Json,新的默认 ASP.NET Core JSON 序列化器。

如果您想切换回使用 Newtonsoft.Json 的先前默认设置,请执行以下操作:

首先安装Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包。然后在ConfigureServices() 中添加对AddNewtonsoftJson() 的调用,如下所示:

public void ConfigureServices(IServiceCollection services)
{
     ...
     services.AddControllers()
          .AddNewtonsoftJson()
     ...
 }

更多详情:ASP.NET Core 3.0 - New JSON serialization

【讨论】:

    【解决方案2】:

    虽然您可以更改默认序列化程序并返回到@TanvirArjel 提到的先前功能Newtonsoft.Json,但理想的情况是使用默认序列化程序System.Text,因为它具有更好的性能。您可以在这里查看:How to migrate from Newtonsoft.Json to System.Text.Json 该错误是由于 Heading 类没有有效的无参数构造函数而导致的,该构造函数应定义如下。

    public class Heading {
        Heading(){
        }
        public string AttrOne {get; set;}
        public string AttrTwo {get; set;}
    }
    

    【讨论】:

      【解决方案3】:

      来自docs

      复杂类型

      A complex type must have a public default constructor and public writable properties to bind. When model binding occurs, the class is instantiated using the public default constructor.
      

      您需要为绑定添加一个无参数构造函数以使用该模型。

      如果您使用可能允许无参数构造函数模型的 NewtonsoftJson,则该行为可能在之前(2.2 和更早版本)对您有效。自 3.0 .NET Core uses the newer System.Text.Json serializer by default.

      【讨论】:

      • @vyas-bharghava 感谢您清理链接!
      猜你喜欢
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2012-08-28
      • 2019-09-13
      • 1970-01-01
      • 2021-06-30
      • 2014-12-23
      • 2017-12-18
      相关资源
      最近更新 更多