我刚刚开始使用R& D来集成调用WebApi的MVC应用程序,我正在编写这两个应用程序。最终将由不同的应用程序调用WebApi,因此我想在此处使用业务逻辑。
我在API服务器上创建了以下简单方法:
[HttpPost]
public HttpResponseMessage Get(ShipmentGetCarrierModel view)
{
var response = Request.CreateResponse<ShipmentGetCarrierModel>(HttpStatusCode.OK, view);
return response;
//return new HttpResponseMessage(HttpStatusCode.OK);
}
我从我的MVC应用程序中调用此方法如下:
public ActionResult GetOrderNumber2(int orderNumber)
{
using (var apiServer = new HttpClient())
{
apiServer.BaseAddress = new Uri("http://localhost:52126");
apiServer.DefaultRequestHeaders.Accept.Clear();
apiServer.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ShipmentGetCarrierModel model = new ShipmentGetCarrierModel();
model.nOrderNumber = 100;
// New code:
HttpResponseMessage response =
apiServer.PostAsync("api/PC/Get",
model,
new JsonMediaTypeFormatter()).Result;
if (response.IsSuccessStatusCode)
{
return Content(response.Content.ToString());
}
}
return Content("NOT " + orderNumber.ToString());
}
我的模型对于两个应用程序都是相同的:
public class ShipmentGetCarrierModel
{
public int nID { get; set; }
public int nOrderNumber { get; set; }
public string cConsigneeName { get; set; }
public string cCarrierCode { get; set; }
public string cConsigneeAddress1 { get; set; }
public string cConsigneeAddress2 { get; set; }
public string cConsigneeCity { get; set; }
public string cConsigneeProvince { get; set; }
public string cConsigneePostalCode { get; set; }
public string cConsigneeTelephone { get; set; }
public string cConsigneeContact { get; set; }
public string cConsigneeCountry { get; set; }
public Boolean? lIsPharmilink { get; set; }
}
我收到了响应代码,但是我看不到WebAPI创建的调试器中返回的模型数据。
具有讽刺意味的是,当我使用Fiddler分析调用时,我看到我的模型带有空值。
显然我在这里遗漏了一些东西。 TIA 标记
答案 0 :(得分:1)
我终于发现了我做错了什么;调用HttpClient后,我错过了两个步骤
public ActionResult GetOrderNumber2(int orderNumber)
{
using (var apiServer = new HttpClient())
{
apiServer.BaseAddress = new Uri("http://localhost:52126");
apiServer.DefaultRequestHeaders.Accept.Clear();
apiServer.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ShipmentGetCarrierModel model = new ShipmentGetCarrierModel();
model.nOrderNumber = 100;
// New code:
HttpResponseMessage response =
apiServer.PostAsync("api/CPC/Get",
model,
new JsonMediaTypeFormatter()).Result;
// I was missing this !!!
string returnResult = response.Content.ReadAsStringAsync().Result;
JavaScriptSerializer JSserializer = new JavaScriptSerializer();
ShipmentGetCarrierModel returnModel = JSserializer.Deserialize<ShipmentGetCarrierModel>(returnResult);
if (response.IsSuccessStatusCode)
{
return Content(returnModel.ToString());
}
}
return Content("NOT " + orderNumber.ToString());
}