© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
4 replies
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
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!
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Asp Net Core Authorize Attribute
C#CC# / help
4y ago
ASP.NET JSON conversion issues
C#CC# / help
3y ago
✅ Asp .NET Core production settings.json question.
C#CC# / help
15mo ago
❔ Access AppSettings.json in asp.net core
C#CC# / help
3y ago