【问题标题】:Properties of user-defined struct not deserialized in .NET Core 3.0 web API (works in .NET Core 2.2)用户定义结构的属性未在 .NET Core 3.0 Web API 中反序列化(适用于 .NET Core 2.2)
【发布时间】:2020-02-06 03:34:45
【问题描述】:

我有一个面向 .NET Core 3.0 的 ASP.NET Core Web API 项目,带有以下控制器:

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();

当进入控制器方法时,foo.Bar 的默认值为 0。我希望它是 1。

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

这在具有基本结构的 .NET Core 3.0 中不再适用(编辑: 由于thispointed out by Martin Ullrich)。但是,如果我使用诸如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));
}

任何帮助将不胜感激。

【问题讨论】:

    标签: asp.net-core .net-core json-deserialization .net-core-3.0 asp.net-core-3.0


    【解决方案1】:

    新的System.Text.Json API 不支持 Newtonsoft.Json(“Json.NET”)提供的所有功能,包括 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 注册它们,请参阅https://stackoverflow.com/a/57334833/784387

    【讨论】:

    • 谢谢 - 这是一个很好的答案,在我解决它之前可以作为临时解决方法,但不能完全回答我提出的问题,即我现在必须做些什么考虑到DateTime 工作正常并且还具有只读属性,我的结构 DateTime 已经支持?
    • 已编辑以包含有关转换器的详细信息。
    • 好的,谢谢您的信息。鉴于存在问题并且为此打开了PR,这可能意味着该问题将通过 readonly 属性上的一个简单属性来解决,我将暂时搁置并继续使用AddNewtonsoftJson 解决方法来创建一个如果上述 PR 获得批准,自定义转换器可能不需要。
    猜你喜欢
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 2020-02-04
    • 2019-08-06
    • 2019-07-31
    相关资源
    最近更新 更多