I'm trying to get automatic data validation working in an ApiController
but when the user sends incorrect/missing data a JSON deserialization failed error message is returned instead of the custom ErrorMessage
.
ProfilesController.cs
using ClassLibrary.Models;
using ClassLibrary.Services;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using ClassLibrary.Models.API.Responses.Profiles;
using ClassLibrary.Models.API.Requests;
using Microsoft.AspNetCore.Authorization;
namespace API.Controllers
{
[ApiController]
[Route("v1/[controller]")]
public class ProfilesController : Controller
{
private IProfileManager _profileManager;
public ProfilesController(IProfileManager profileManager)
{
_profileManager = profileManager;
}
[Authorize]
[HttpPatch("about")]
public async Task<IActionResult> UpdateAbout([FromBody] UpdateAboutPayload payload)
{
await _profileManager.UpdateAboutAsync(payload.About);
return Ok();
}
}
}
UpdateAboutPayload.cs
using System.ComponentModel.DataAnnotations;
namespace ClassLibrary.Models.API.Requests
{
public class UpdateAboutPayload
{
[Required(ErrorMessage = "About is required")]
[StringLength(500, ErrorMessage = "About must be between 0 and 500 characters long")]
public required string About { get; set; }
}
}
When I send the following data
{}
I get this error
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"$": [
"JSON deserialization for type 'ClassLibrary.Models.API.Requests.UpdateAboutPayload' was missing required properties, including the following: about"
],
"payload": [
"The payload field is required."
]
},
"traceId": "00-402c938fa2cb172de6a89b521f8fcae1-88ebfe9d6c674e35-00"
}
instead of the error message configured in the [Required]
attribute
The issue was caused by the required
modifier on the About
property, removing it solved the error.