When you have an API where the body is not optional or nullable like this
[HttpPut("{postId}")]
public async Task<IActionResult> Update(
[FromRoute] string postId,
[FromBody] UpdatePostRequest request)
{
// Logic to update post
...
return NoContent();
}
If a client sends a request to this endpoint without Content-Type and body, they would get this error
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.16",
"title": "Unsupported Media Type",
"status": 415,
"traceId": "00-92b30b239eca44beb048a4923d145cfc-4a150c0e97824d78-00"
}
And if the request has Content-Type in the headers, then this error will be returned
{
"type": "https://datatracker.ietf.org/doc/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-ded02a7403fd42ca8880e92f6963fc10-5ec659fe255b420e-00",
"errors": {
"": [
"A non-empty request body is required."
]
}
}
If you want to validate whether the request is empty manually in the controller so you can return a custom response, you can do the following
[HttpPut("{postId}")]
public async Task<IActionResult> Update(
[FromRoute] string postId,
[FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] UpdatePostRequest request)
{
if (request == null)
{
// return some custom response.
}
// Logic to update post
...
return NoContent();
}
You can also allow Empty body globally. In your startup class, add the following
services.AddMvc()
.AddMvcOptions(o => o.AllowEmptyInputInBodyModelBinding = true);