Reputation: 1255
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
Upvotes: 0
Views: 3055
Reputation: 1255
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;
}
Upvotes: 1