简体   繁体   中英

Submitting object parameter to WebAPI using HttpClient from client app

I wanted to share with the community about an issue I had to overcome when working with a console app and communicating with a WebAPI service call.

Passing simple types as parameters is straight forward but passing a complex type wasn't as simple. I needed to serialize the type somehow and pass that as a parameter. My approach is as follows. I hope someone finds this useful

WebAPI method:

      public IHttpActionResult PurchaseOrders([FromUri]string parameters)
      {
      var criteria = new JavaScriptSerializer().Deserialize<PurchaseOrderManager.Criteria>(parameters);
      var result = PurchaseOrderManager.PurchaseOrderSummary(criteria);
      return Content(HttpStatusCode.OK, result);
      }

The client method calling the service...

 private static async Task<List<PurchaseOrderListModel>> GetPendingPurchaseOrdersByUser(string token, UserModel userModel)
{
    var service = ConfigurationManager.AppSettings["service:address"];

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(service);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

        var content = new StringContent(JsonConvert.SerializeObject(new
        {
            Filter = "PENDING",
            RequestType = "REQUEST"
        }), Encoding.UTF8, "application/json");
        var paramsValue = content.ReadAsStringAsync().Result;


        HttpResponseMessage response = await client.GetAsync($"purchaseorders/purchaseorders?parameters={paramsValue}");
        if (response.IsSuccessStatusCode)
        {

            var purchaseOrders = response.Content.ReadAsAsync<List<PurchaseOrderListModel>>().Result;
            //do work....
            //return some value
        }
    }
    return null;
}

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