我想与社区分享在使用控制台应用程序和与WebAPI服务调用进行通信时必须克服的问题。
将简单类型作为参数传递是直接的,但传递复杂类型并不简单。我需要以某种方式序列化类型并将其作为参数传递。我的方法如下。我希望有人发现这个有用的
答案 0 :(得分:1)
WebAPI方法:
public IHttpActionResult PurchaseOrders([FromUri]string parameters)
{
var criteria = new JavaScriptSerializer().Deserialize<PurchaseOrderManager.Criteria>(parameters);
var result = PurchaseOrderManager.PurchaseOrderSummary(criteria);
return Content(HttpStatusCode.OK, result);
}
调用服务的客户端方法......
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;
}