【发布时间】: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 中不再适用(编辑: 由于this 为pointed 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