Json post int type always 0

[HttpPost("method")]
public string Method(int number)
{
    return number.ToString();
}

Why is the number always 0?

Is it possible to use a json post with such primitive types?

My post: {"number": 3}

+4
source share
2 answers

If you post type data { "number" : 3 }, your action method should be

public class Data
{
   public int Number {get; set;}
}

[HttpPost("method")]
public string Method([FromBody] Data data)
{
    return data.Number.ToString();
}
+2
source
public class NumberModel
{
    public int Number { get; set; }
}

[HttpPost("method")]
public IActionResult Method([FromBody] NumberModel model)
{
    return Ok(model.Number);
}

Will automatically format it as Json. Since Number is an integer, it will be returned as a string representation of the number. If you just return Ok(model)it will return a json object like{ 'Number' : 3 }

+1
source

Source: https://habr.com/ru/post/1681728/


All Articles