Reputation: 1809
I have a POST method in my WebApi that takes json string as parameter.
[HttpPost]
public HttpResponseMessage GetOrderDataBySessionId([FromBody] string json)
I tried hitting it using RestClient with URL: localhost:56934/api/Home/GetOrderDataBySessionId
and specifying following json string in the Body:
{
"ListSessionId": [
"180416073256DGQR10",
"180416091511DGQR10"
]
}
setting the body/content type as application/json. But when it hits my method, the json
string parameter is always null.
Is it because I need to use a complex type in parameter?
Can we never have input in string?
Upvotes: 1
Views: 2035
Reputation: 1
I have resolved this problem.
Code in client:
$.ajax({
url: "/api",
type: "post",
data: "p1=1&p2=2"
});
code in server:
[HttpPost]
public string Post([FromForm] string p1, [FromForm] string p2)
{
return p1+p2;
}
There are three key points:
[FromForm]
instead of [FromBody]
in front
of the parameter.Upvotes: 0
Reputation: 23190
By sending this content:
{
"ListSessionId": [
"180416073256DGQR10",
"180416091511DGQR10"
]
}
You're sending a JSON represented with a proprerty ListSessionId
typed as an array of string so your Web API action should be:
public HttpResponseMessage GetOrderDataBySessionId([FromBody] List<string> listSessionId)
Just change the string json
to List<string> listSessionId
.
Upvotes: 2