Reputation: 439
Using .NET 6.0. When trying to bind a parameter to a body of the request, I want to assign a value of null
to the properties that aren't included in the request.
Consider the following:
public class SomeRequest
{
[JsonProperty(PropertyName = "property1")]
public string prop1 { get; set; }
[JsonProperty(PropertyName = "property2")]
public string prop2 { get; set; }
}
[Route("[controller]")]
[ApiController]
public class MyController : ControllerBase
{
[HttpPost]
public async Task<SomeResponse> Post([FromBody] SomeRequest value1)
{
}
}
If I send the following request {"property1":"abc"}
, I want value1
to be {"property1":"abc","property2":null}
, but instead I get an HTTP 400 with an error message that property2
is required.
What is the best way to make it so that property2 is null
? I am pretty sure that it worked like this in .NET Core 3.1.
Thank you
Upvotes: 2
Views: 4687
Reputation: 628
.NET 6 projects have nullable context enabled by default - meaning prop2 is treated as a non-nullable string.
To behave as you're expecting, either:
string?
)<Nullable>disable</Nullable>
in the csproj)
Upvotes: 4