Pass parameters to HttpPost method of controller

1.7k views Asked by At

There something very basic i must be missing which i cant understand what it is. I have a method at the controller

    [Route("SomeMethod")]
    [HttpPost]
    public IActionResult SomeMethod([FromBody]int interval)
    {
        ...
    }

And im seing with postman post request {"interval": 2000 }, The interval at the controller is not initialized. If i change the method paramater to be object i get ValueKind = Object : "{"interval": 2000 }"

I also tried the parameter to be string and then the body i sent is {"interval": "2000" }, And at the controller i get null

Based on this question i tried:

[Route("SomeMethod")]
[HttpPost]
public IActionResult SomeMethod([FromBody]JsonElement interval)
{
    ...
}

And got ValueKind = Undefined : "" At the contoroller, And also:

services.AddControllers()
        .AddNewtonsoftJson();

When the method expects an int and got 0

1

There are 1 answers

0
maxs87 On

According to documentation you have to pass it in request body as it is, just a value, without property name. But its imposible to bind more then one parameter. Anyway, I would reccomend to use proper object to bind body parameters.

[Route("SomeMethod")]
[HttpPost]
public IActionResult SomeMethod([FromBody]Request request)
{
    return Ok();
}


public class Request
{
    public int Interval { get; set; }
}