Search code examples
c#.net.net-coreasp.net-web-api2.net-6.0

Web API C# how to allow post for an object model if its an optional field


I am new to Web API. I am trying to see if we can submit a POST request without optional fields.

My object model

public class MyAddress
    {
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string State { get; set; }
        [JsonProperty( NullValueHandling = NullValueHandling.Ignore )]
        public string City { get; set; }
    }

This is my Controller

[Route( "api/[controller]" )]
[ApiController]
public class AddressController : ControllerBase
{
    [HttpPost]
    [ProducesResponseType( typeof( MyAddressDto ), 200 )]
    public async Task<IActionResult> PostAsync( MyAddress address )
    {
        return Created( string.Empty, "Call received" );
    }
}

Is there a way POST request can default to Null if the State and City fields are not supplied in FormBody?

Example POST request:

curl -X 'POST' \
  'https://localhost:7088/api/Address' \
  -H 'accept: text/plain' \
  -H 'Content-Type: application/json' \
  -d '{
  "address1": "address line 1",
  "address2": "address line 2",
  "city": "city"
}'

This is the error message I receive for the above POST

{
  "errors": {
    "State": [
      "The State field is required."
    ]
  },
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-cd38c09edb586fcfcf155732f3af8f14-421285519485f996-00"
}

At present I am unable to make a successful POST call without passing the field State and City.

I am using NewtonsoftJson 6.0.20

Thanks!


Solution

  • If fields are optional mark them as ones via nullable reference types (i.e. string -> string?) :

    public class MyAddress
    {
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string? State { get; set; }
        [JsonProperty( NullValueHandling = NullValueHandling.Ignore )]
        public string? City { get; set; }
    }