0

I have an Api Action defined as follows:

public async Task<IActionResult> AddCountry([FromBody] CountryDto country)
{
    // create the country
}
public class CountryDto
{
    public Guid Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

When I use the payload below, it gets casted to a CountryDto type.

{
  "id": "a05ddfdb-07ba-442b-9dd4-1392adf2ee5c",
  "code": "CA",
  "name": "Canada",
}

However, if I enter an invalid value that can't be casted like so

{
  "id": 2,
  "code": "CA",
  "name": "Canada",
} 

The countryDto parameter becomes null due to invalid casting. Is there a way for me to make the casting fail throw an exception instead of silently failing?

evablack
  • 117
  • 1
  • 2
  • 9
  • You can check to see if the parameter is null right at the beginning and throw an exception. Or, do you want something fancier? – Doug Dawson Feb 01 '18 at 04:17
  • you might want look at related posts like https://stackoverflow.com/questions/20224630/api-controller-passed-invalid-json-receives-null – TheGeneral Feb 01 '18 at 04:21
  • In fact this is nearly bordering on duplicates of several others – TheGeneral Feb 01 '18 at 04:22
  • @DougDawson I was actually wondering if there was a way I could split up up the actual request so I could indicate which specific field was suspect instead of the just saying that a bad request has been made. – evablack Feb 01 '18 at 22:36

0 Answers0