public class Car{ [JsonConstructor] public Car(string brand) { ArgumentException.ThrowIfNullOrWhiteSpace(brand); Brand = brand; } [JsonProperty("brand")] public string Brand { get; }}
public class Car{ [JsonConstructor] public Car(string brand) { ArgumentException.ThrowIfNullOrWhiteSpace(brand); Brand = brand; } [JsonProperty("brand")] public string Brand { get; }}
It works just fine.
An issue occurs whenever I got code like this:
[ApiController]public class CarsController : ControllerBase{ [HttpPost] public IActionResult CreateCar([FromBody] Car car]) { // [...] }}
[ApiController]public class CarsController : ControllerBase{ [HttpPost] public IActionResult CreateCar([FromBody] Car car]) { // [...] }}
Binding the model fails now (because the constructor of
Car
Car
is throwing an exception) which results in an HTTP status code 500 (Internal Server Error) instead of my desired 400 (Bad Request).
My current idea (I don't like it): Create a copy of that class without the JSON attributes but with DataAnnotations. Do you have any other ideas?