Why is my controller hit when the fluentvalidation for the model is not valid in ASP.Net Core?

Finally found the problem. The issue in my case was that I was missing the [ApiController] attribute at the top of my controller:

    [ApiController] // <-- Fix is here
    [Route("[controller]")]
    public class SectionController : ControllerBase
    {

        [HttpPost]
        public async Task<IActionResult> Post([FromBody] DtoArticle request)
        {
            var ms = ModelState;
            if (!ms.IsValid)
                throw new Exception("Should not be possible");

            return Ok();
        }
    }

My controller is no longer hit and I instead get a tidy response from Postman:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|f5f5b1a2-4dd202e6998784c3.",
    "errors": {
        "Name": [
            "'Name' is required."
        ],
        "Content": [
            "'Content' is required."
        ]
    }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top