Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient pass multiple simple parameters

I'm trying to do a POST from one controller to another controller. Both controller's are from different projects. One project is serving to simulate the presentation layer (which I will call the test project here).

From the test project I'm trying to pass 2 simple string parameters to the other controller which I will call the process.

var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("id", param.Id.Value));
values.Add(new KeyValuePair<string, string>("type", param.Type.Value));
var content = new FormUrlEncodedContent(values);
using (var client = new HttpClient())
{
       client.BaseAddress = new Uri(url);
       client.DefaultRequestHeaders.Clear();
       client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("nl-NL"));

       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

       string token = param.token.Value;
       client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

       var response = client.PostAsync("/api/Process/Product", content).Result;

       if (response.IsSuccessStatusCode)
       {
           var result = response.Content.ReadAsStringAsync().Result;
           return Request.CreateResponse(HttpStatusCode.OK, result);
       }

       return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "fail");
}

And in the process controller, I'm trying to receive it like this:

[HttpPost]
public HttpResponseMessage Product(string id, string type)
{
    return null;
}

But it never reaches this controller. I always get a "not found status code".

So how can I pass 2 simple parameters with HttpClient()?

like image 702
Quoter Avatar asked Oct 16 '14 11:10

Quoter


People also ask

How do I pass multiple parameters to an API request?

At most one parameter is read from the message body in the web api framework. Therefore If there are multiple parameters then create a class wrapping all the stuffs required for the api request in that calss. Create an instance of this class and pass this when you call the api call.

Are all methods with httpclient asynchronous?

All methods with HttpClient are asynchronous. HttpClient class provides a base class for sending/receiving the HTTP requests/responses from a URL. It is a supported async feature of .NET framework. HttpClient is able to process multiple concurrent requests. It is a layer over HttpWebRequest and HttpWebResponse.

How to pass multiple complex types to a web API controller?

For passing multiple complex types to your Web API controller, add your complex types to ArrayList and pass it to your Web API actions as given below-

Is it better to have a single httpclient or multiple httprequestmessage?

Further, results suggest this also has better performance with more than 12% improvement based on the load. For multiple requests of different payloads, having a single instance HttpClient but a new HttpRequestMessage for every request looked a good approach to use.


2 Answers

Use Get instead of Post for simple type parameters.

    using (var client = new HttpClient())
    {
        BaseAddress = new Uri(url);
        client.BaseAddress = new Uri(url);
   client.DefaultRequestHeaders.Clear();
   client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("nl-NL"));

   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

   string token = param.token.Value;
   client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        // New code:
        var response = await client.GetAsync( string.format("api/products/id={0}&type={1}",param.Id.Value,param.Id.Type) );
 if (response.IsSuccessStatusCode)
   {
       var result = response.Content.ReadAsStringAsync().Result;
       return Request.CreateResponse(HttpStatusCode.OK, result);
   }

   return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "fail");

    }

In the API side you can do like this.

[HttpGet]
public HttpResponseMessage Product(string id, string type)
{
  return null;
}
like image 160
NMK Avatar answered Oct 30 '22 09:10

NMK


When receiving a post you must specify [FromBody] in the parameters for the method to be called

[HttpPost]
public HttpResponseMessage Product([FromBody]string id, [FromBody]string type)
{
    return null;
}
like image 22
Brady Jerin Avatar answered Oct 30 '22 10:10

Brady Jerin