Mike R. Mike R. - 1 month ago 17
C# Question

Postman using Put

Trying to do Put using Postman, can't seems to figure it out:

I have this method, which triggers a break point and everything is good:

public IHttpActionResult Put(User user)
{
// ... code ...
return StatusCode(HttpStatusCode.NoContent);
}


In a Postman:

url: .../api/users/2
Headers(1): Content-Type application/json,
Body:
{
"id": "1",
"login": "Test",
"pass": "1"
}


... the usual stuff, etc ...

It works, but NOW I need to change the method to

public IHttpActionResult Put(int key, User user)
{
// ... code ...
return StatusCode(HttpStatusCode.NoContent);
}


I tried everything in a body of message using Postman, nothing makes it trigger the break-point. How do I have that key passed in along with user object???

Needed to add [FromBody] also because my routeTemplate: "api/{controller}/{id}" is like this, I changed method definition from key to id, that way I can call Put using the following url .../api/users/3

Answer

You need to use [FromBody]. The following is the working code which I use with HttpPost

[HttpPost("ByYear")]
public async Task<IActionResult> GetStudentDetailByYear([FromBody]SearchStudentModel model)
{
   if (string.IsNullOrWhiteSpace(model.query)
       || string.IsNullOrWhiteSpace(model.AcademicYearID))
       return BadRequest("Required Parameter not provided");

      // some codes to handle the query
 }