concentriq
concentriq

Reputation: 439

ASP.NET Core Web API: how to assign value of null to a missing property in the request when parameter binding

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

Answers (1)

Tonu
Tonu

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:

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

Upvotes: 4

Related Questions