.NET Core 3.0 web 中未反序列化的用户定义结构的属性 API(适用于 .NET Core 2.2)

Properties of user-defined struct not deserialized in .NET Core 3.0 web API (works in .NET Core 2.2)

我有一个 ASP.NET Core web API 项目,目标是 .NET Core 3.0,带有以下控制器:

public class FooController : ControllerBase
{
    [HttpPost]
    public ActionResult Post(Foo foo) => Ok()
}

Foo 在单独的库中定义为:

public struct Foo
{
    public int Bar { get; }

    public Foo(int bar) => Bar = bar;
}

我从控制台应用程序调用 API:

new HttpClient().PostAsJsonAsync("http://localhost:55555/api/foo", new Foo(1)).Wait();

进入controller方法时,foo.Bar默认值为0,我希望是1。

这曾经在 .NET Core 2.2 中按预期工作。 JSON 反序列化器通过重载构造函数处理结构上带有私有 setter 的属性,其参数名称与 属性 名称匹配(不区分大小写)。

这在具有基本结构的 .NET Core 3.0 中不再有效(编辑: 由于 this as )。但是,如果我使用 DateTime 等标准结构类型,它就可以正常工作。我现在必须对 DateTime 已经支持的结构做一些额外的事情吗?我已经尝试使用下面的代码在 Foo 上实现 ISerializable,但这没有用。

public Foo(SerializationInfo info, StreamingContext context)
{
    Bar = (int)info.GetValue("bar", typeof(int));
}

public void GetObjectData(SerializationInfo info, StreamingContext context)
{
    info.AddValue("bar", Bar, typeof(int));
}

如有任何帮助,我们将不胜感激。

System.Text.Json APIs do not support all the features that Newtonsoft.Json ("Json.NET") does, including deserialisation of read-only properties.

如果您需要此功能,请按照 Migrate from ASP.NET Core 2.2 to 3.0 指南中的说明切换到使用 Newtonsoft.Json:

services.AddMvc()
    .AddNewtonsoftJson();

services.AddControllers()
    .AddNewtonsoftJson();

DateTime 已经为 3.0 中的 System.Text.Json 堆栈所知,并且还有一个 JsonConverter<T> 实现:JsonConverterDateTime.

要创建自定义转换器并为 ASP.NET Core 注册它们,请参阅