I have an ASP.NET Core web API project targeting .NET Core 3.0 with the following controller:
public class FooController : ControllerBase
{
[HttpPost]
public ActionResult Post(Foo foo) => Ok()
}
Foo
is defined in a separate library as:
public struct Foo
{
public int Bar { get; }
public Foo(int bar) => Bar = bar;
}
I call the API from a console app with:
new HttpClient().PostAsJsonAsync("http://localhost:55555/api/foo", new Foo(1)).Wait();
When the controller method is entered, foo.Bar
has the default value of 0. I expect it to be 1.
This used to work as expected in .NET Core 2.2. The JSON deserializer handles properties with private setters on structs via an overloaded constructor with parameter names matching the property names (case-insensitive).
This no longer work in .NET Core 3.0 with basic structs (EDIT: due to this as pointed out by Martin Ullrich). However, if I use a standard struct type such as DateTime
, it works fine. Is there something additional I must now do to my struct that DateTime
for instance already supports? I've already tried implementing ISerializable
on Foo
with the code below, but that didn't work.
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));
}
Any help would be greatly appreciated.