Huma Ali
Huma Ali

Reputation: 1809

WebApi POST method with string parameter is always null

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

Answers (2)

Winter's Love
Winter's Love

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:

  1. The parameter name must be the same both in client and server.
  2. In the client, there must be [FromForm] instead of [FromBody] in front of the parameter.
  3. You can add multiple parameters even, but the parameter names must correspond.

Upvotes: 0

CodeNotFound
CodeNotFound

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

Related Questions