Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass null in body to endpoint within asp.net core 3.1

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?

like image 396
Kevin Smith Avatar asked Jan 19 '20 18:01

Kevin Smith


People also ask

Can you pass null for object?

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.

Why to use FromBody in Web API?

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).

Why your FromBody parameter is always null?

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 .


1 Answers

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)
like image 156
Kevin Smith Avatar answered Sep 19 '22 12:09

Kevin Smith