C#C
C#2y ago
qqdev

✅ JSON + ASP.NET attribute usage

Hi! My JSON class looks like this:
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])
  {
    // [...]
  }
}


Binding the model fails now (because the constructor of 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?


Thanks in advance!
Was this page helpful?