通过HTTPS调用REST API时出现500 Server错误

时间:2015-03-25 16:45:37

标签: c# xml rest fiddler dotnet-httpclient

我使用此代码将XML发布到REST网络服务,但我只是得到一个模糊的“500服务器错误”。如果我将相同的XML粘贴到Fiddler中它可以很好地工作,那么我做错了什么?

using (var client = new HttpClient())
{
   var httpContent = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
   var response = client.PostAsync(new Uri("httpsapiurl"),httpContent).Result;
   if (response.IsSuccessStatusCode)
   {
       // EDITED: this isn't hit as IsSuccessStatusCode is always false
       //Stream stream = await response.Content.ReadAsStreamAsync();
   }
}

1 个答案:

答案 0 :(得分:0)

您是否需要在请求中设置内容类型?

try
{
    var httpClient = new HttpClient();
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
    HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, URL);
    req.Content = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
    await httpClient.SendAsync(req).ContinueWith(async respTask =>
    {
        Debug.WriteLine(req.Content.ReadAsStringAsync());
    };
}
catch (Exception ex) 
{ 
}

特别是这条线很重要。我没有遇到类似的问题,当没有设置Content-Type标头时,拒绝吐出任何东西。

 req.Content = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");

不知道它是否有帮助。