I am trying to retrieve ModelState
validation errors from a micro service built with .NET Core 5 Web API from a ASP.NET Core MVC frontend.
Say I have a model that looks like this:
public class Comment
{
public string Title { get; set; }
[Required]
public string Remarks { get; set; }
}
When I call the rest endpoint in the micro service through Swagger to update the Comment
model without a remark, I get a response body like this:
{
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"Remarks": [
"The Remarks field is required."
]
}
}
Awesome! This is what I expect... However, when I call this endpoint through my MVC project, I can't seem to get the actual "errors".
This is how I am calling the rest endpoint:
var client = _httpClientFactory.CreateClient("test");
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(comment), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PutAsync($"api/comments", httpContent);
The response object just has a statusCode
of BadRequest
. I want to pull the info regarding the errors (the section that says "The Remarks field is required.") but I don't see it in the Content
or Headers
property or anything like that.
I am new to micro services and .NET Core - am I doing something wrong? Do I need to add something to the startup.cs
? Seems weird that I can get the BadRequest
status but no supporting problem details.
Thanks in advance!
Be sure your web api controller is not declared with [ApiController]
.
Web Api Project:
//[ApiController]
[Route("api/[controller]")]
public class CommentsController : ControllerBase
{
[HttpPut]
public IActionResult Put([FromBody] Comment model)
{
if(ModelState.IsValid)
{
//do your stuff...
return Ok();
}
return BadRequest(ModelState);
}
}
Mvc Project:
HttpResponseMessage response = await client.PutAsync($"api/comments", httpContent);
var result = response.Content.ReadAsStringAsync().Result;