2

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
concentriq
  • 359
  • 2
  • 6
  • 16

1 Answers1

4

.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:

  • Make prop2 nullable (string?)
  • Disable the nullable context at the project level (<Nullable>disable</Nullable> in the csproj)
    • This can also be done at the source code level using pre-processor directives, but it isn't applicable in your use-case.
Tonu
  • 493
  • 6
  • 14