简体   繁体   中英

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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM