I have the following action within an asp.net core 3.1 controller
[ApiController]
[Route("example")]
public class MyExampleController : ControllerBase
{
[HttpPost("{id}/value")]
public async Task<IActionResult> Post(string id, [FromBody] int? value)
=> Task.FromResult(Ok());
}
This works fine if I post a body value of int (for example: 1
, 2
, etc...)
However, I can't find a way to get a null
value passed in.
If I pass in an empty body or null
body I get a status code of 400 returned with a validation message of A non-empty request body is required.
returned.
I've also tried to change the value
parameter to be an optional argument with a default value of null
:
public async Task<IActionResult> Post(string id, [FromBody] int? value = null)
How do I pass in null to this action?
It is absolutely fine to pass null to methods. However, if you have a csae where you might not need to pass a variable, consider overloading.
Using [FromBody]When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).
Web API reads the response body at most once, so only one parameter of an action can come from the request body. If you need to get multiple values from the request body, define a complex type. But still the value of email is NULL .
Finally figured this out, big thanks to @Nkosi and @KirkLarkin helping fault find this.
Within the Startup.cs
when configuring the controllers into the container we just need to alter the default mvc options to AllowEmptyInputInBodyModelBinding
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(x => x.AllowEmptyInputInBodyModelBinding = true);
}
This way we can pass in null
into the body of the post and it works perfectly fine. It also still applies the normal model validation via the attributes without having to check the ModelState manually:
public async Task<IActionResult> Post(string id,
[FromBody][Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than 1")]
int? value = null)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With