Akash Kumar
Akash Kumar

Reputation: 55

How to pass Json data as parameter to web api using HttpClient

I am using one asp.net application where i am calling web api using HttpClient.

in web API controller i am passing two parameter one is int and second is string.

Below is the code:

public HttpResponseMessage Get(int submissionID, string jsonData)
{

}

This is working fine no issues when i am passing one int and one string parameter using httpClient

Below is my httpClient code:

public void GetWebApiData(int fileID, String jsonData)
{
    var client = new HttpClient();
    var task = client.GetAsync("http://localhost:1469/api/Smartling/" + fileID + "/"+jsonData)
      .ContinueWith((taskwithresponse) =>
      {
          var response = taskwithresponse.Result;
          var jsonString = response.Content.ReadAsStringAsync();
          jsonString.Wait();
          var getVal = jsonString.Result;

      });
    task.Wait();
} 

in the above code if i am passing instead of json data it's giving error response code 400 Bad Request.

same I used with jQuery ajax call and it's working fine no issues.

How to pass JSON data as parameter?

Upvotes: 3

Views: 7616

Answers (2)

Ravi A.
Ravi A.

Reputation: 2213

Say you have a class

public class Sample
{
    public string Value1 { get; set; }
    public string Value2 { get; set; }
}

On the client side

public async static Task<Boolean> GetWebApiData(int fileID,string jsonData)
{
    var client = new HttpClient();
    Sample model = new Sample();
    model = Newtonsoft.Json.JsonConvert.DeserializeObject<Sample>(jsonData);
    var response = await client.GetAsync(string.Format("http://sample.com/api/test/{0}?model.value1={1}&model.value2={2}", fileID ,model.Value1, model.Value2));
    if (response.StatusCode == HttpStatusCode.OK)
        return true;
    else
        return false;
}

On the server side

[HttpGet]
public IHttpActionResult Get(int id,[FromUri]Sample model)
{
    //do something
    return Ok();
}

Upvotes: 4

arunraj770
arunraj770

Reputation: 827

Also please use "string" instead of "String" class in

public void GetWebApiData(int fileID, String jsonData)

if not working

Please try stringify or SerializeObject() to convert that data before you pass the data as argument.

something like JSON.stringify(jsonData); or JsonConvert.SerializeObject(jsonData);

Upvotes: -1

Related Questions