1

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?

3
  • 2
    If you expect a string, format it as one in the body. Now you are sending a json object, not a string. Commented Apr 25, 2018 at 7:26
  • 2
    That is not a string you are sending it's an object, use this for a string "{ \"ListSessionId\": [ \"180416073256DGQR10\", \"180416091511DGQR10\" ] }" Commented Apr 25, 2018 at 7:26
  • @AdeoluwaSimeon Now I know what I was doing wrong.Thanks, Works now :) Commented Apr 25, 2018 at 7:30

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.