WEBException未处理:远程服务器返回错误:(500)内部服务器错误

时间:2015-05-15 10:23:58

标签: c# post httpwebrequest webclient

我正在实施REST服务,我收到了上述错误。我搜索了很多并使用不同的方法来解决这个错误,但没有运气。当我使用Postman或fiddler时,该服务正常。 POSTMAN Fiddler

这是我的代码:

try
{
  string content = string.Empty;
  var httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri("https://api.MYDOMAIN.com/servlet/Year"));
  httpWebRequest.Method = "POST";
  string parsedContent = "{\"securitykey\":\"KEY\"}";
  var data = JObject.Parse(parsedContent);
  Byte[] bytes = Encoding.UTF8.GetBytes(data.ToString());
  httpWebRequest.ContentLength = bytes.Length;
  httpWebRequest.ContentType = "application/json";
  Stream newStream = httpWebRequest.GetRequestStream();
  newStream.Write(bytes, 0, bytes.Length);
  newStream.Close();
  var response = (HttpWebResponse)httpWebRequest.GetResponse();
  var stream = response.GetResponseStream();
  if (stream != null)
  {
    var sr = new StreamReader(stream);
    content = sr.ReadToEnd();
  }
}
catch (WebException ex)
{
  throw;
}

所以在上面的代码中我尝试了:

httpWebRequest.ContentType = "application/x-www-form-urlencoded";
HttpUtility.UrlEncode()

我也试过下面的代码,但它给了我同样的错误:

using (var client = new WebClient())
{
  client.Headers[HttpRequestHeader.ContentType] = "application/json";
  result = client.UploadString("https://api.MYDOMAIN.com/servlet/Year", "POST", "{\"securitykey\":\"MYKEY\"}");
}

我在原始标题中添加了安全密钥httpWebRequest.Headers.Add("{\"securitykey\":\"MYKEY\"}"),但仍然没有运气。

真的很感激,如果我能得到一些帮助。

1 个答案:

答案 0 :(得分:0)

在很多RND之后我尝试在PHP中这样做,所以它给了我一个错误,因为需要UserAgent。我添加了httpWebRequest.UserAgent并且它有效。此错误从未在WebException中显示。