Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET core - how to pass optional [FromBody] parameter?

How do I pass optional (nullable) [FromBody] parameter in ASP.NET Core (5.0)? If I don't send body in my request I get 415 Unsupported Media Type error. Can this be configured and if so, how to do it on a controller or action, rather than an app level? I presume it has to do something with model validation, but not sure. Thanks.

[HttpGet("[action]")]
public async Task<IActionResult> GetElementsAsync([FromBody] IEnumerable<int> elements = default)
{
  var result = await dataService.GetData(elements);
  return Ok(result);
}

EDIT: To clarify:

This is typical scenario and it works normally: This is typical scenario and it works normally

But passing empty body is returning 415 right away without even reaching action: Passing empty body is returning 415 right away without reaching action

like image 907
Pawel Avatar asked Nov 27 '25 10:11

Pawel


1 Answers

You can find a solution here:
https://github.com/pranavkm/OptionalBodyBinding

From this issue on github:
https://github.com/dotnet/aspnetcore/issues/6878

And from .net Core 5 you can use this one:

public async Task<IActionResult> GetElementsAsync([FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] IEnumerable<int> elements = default)
...

Also needed (from Pawel experience):

services.AddControllers(options =>{options.AllowEmptyInputInBodyModelBinding = true;})
like image 100
Nicola Biada Avatar answered Nov 30 '25 00:11

Nicola Biada