C
C#2mo 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; }
}
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 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!
2 Replies
Angius
Angius2mo ago
You should be using model validation here Not throwing exceptions from the ctor
qqdev
qqdev2mo ago
Thanks, I ended up with creating an adjusted copy of that class Throwing in the ctor is no good (as you pointed out) although it makes sense in our case