I am developing a WebApi using aspnet core. I have been able to setup a basic project and get requests are working well.
Now I am trying to POST a complex JSON object to the API using postman. The API code is like:
//controller class
public class DemoController : ControllerBase {
[HttpPost]
public IActionResult Action1([FromBody]TokenRequest request) {
/* This works. I get request object with properties populated */
}
[HttpPost]
public IActionResult Action2(TokenRequest request) {
/* The request is received. But properties are null */
}
}
//TokenRequest Class
public class TokenRequest {
public string Username { get; set; }
public string Password { get; set; }
}
Tried to test the same with postman.
Request 1: (Fail for both Action1 and Action2)
POST /Demo/Action2 HTTP/1.1
Host: localhost:5001
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 42642430-bbd3-49ca-a56c-cb3f5f2177cc
{
"request": {
"Username": "saurabh",
"Password": "******"
}
}
Request 2: (Success for Action1, Fail for Action2)
POST /User/Register HTTP/1.1
Host: localhost:5001
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 94141e01-7fef-4847-953e-a9acb4e6c445
{
"Username": "saurabh",
"Password": "******"
}
The things are working with Action1 due to the [FromBody[ tag. But what in case I need to accept multiple parameters? like
public IActionResult Action1(int param1, TokenRequest request)
Option 1: Use a wrapper class (as suggested by Francisco Goldenstein)
[FromBody] cannot be used with two different parameters. Is there any graceful solution where I can accept them as separate parameters in the Action method?