Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 940
Akash Kumar Avatar asked Aug 17 '26 09:08

Akash Kumar


1 Answers

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();
}
like image 192
Ravi A. Avatar answered Aug 19 '26 05:08

Ravi A.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!