【问题标题】:Expecting JSON/XML data in Webapi期望 Webapi 中的 JSON/XML 数据
【发布时间】:2016-02-11 11:50:49
【问题描述】:

当我请求一个 webapi 请求时,我收到了 Expecting JSON/XML data 之类的错误

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();
}

【问题讨论】:

  • 上述错误如何解决?
  • 可能是服务器引发了异常,因为您发送了错误的内容类型。或者也许你错过了正确的 Accept Header

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


【解决方案1】:

我建议使用 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;
}

【讨论】:

    猜你喜欢
    • 2017-03-14
    • 2016-02-07
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2021-05-28
    • 2017-06-05
    相关资源
    最近更新 更多