期待Webapi中的JSON / XML数据

时间:2016-02-11 11:50:50

标签: c# asp.net-web-api webrequest httpwebresponse

当我请求一个webapi请求时,我收到了诸如期望JSON / XML数据

之类的错误
try         
{                
    string oRequest = _xml.UpdateInvereqxml(UserName, Password,OTAhotelid, Invy);                
    string uri = @"service/update";
    System.Net.WebRequest req = System.Net.WebRequest.Create(uri);
    req.Method = "POST";
    req.ContentType = "text/xml";
    System.IO.StreamWriter writer = new System.IO.StreamWriter(req.GetRequestStream());
    writer.WriteLine(oRequest);
    writer.Close();
    System.Net.WebResponse rsp = req.GetResponse();
    Stream istrm = rsp.GetResponseStream();
    string StreamReader = new StreamReader(istrm).ReadToEnd();
}

1 个答案:

答案 0 :(得分:0)

我建议使用HttpClient与ASP.NET Web API进行通信。该类提供了许多用于处理REST服务(example

的函数
public EnumProduct Post(EnumProduct product)
{
HttpResponseMessage reponse = httpClient.PostAsJsonAsync("api/enumproducts/Post", product).Result;
if (reponse.IsSuccessStatusCode)
{
var enumProduct = reponse.Content.ReadAsAsync().Result;
return enumProduct;
}
else
return null;
}