WEBException was unhandled: The remote server returned an error: (500) Internal Server Error

WEBException was unhandled: The remote server returned an error: (500) Internal Server Error

我正在实施 REST 服务,但出现上述错误。我进行了很多搜索并使用了不同的方法来解决此错误,但没有成功。当我使用 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\"}");
}

我在原始 header 中添加了安全密钥作为 httpWebRequest.Headers.Add("{\"securitykey\":\"MYKEY\"}") 但仍然没有成功。

如果能得到一些帮助,我将不胜感激。

经过多次 RND 我尝试在 PHP 中执行此操作,因此它给了我一个错误,因为需要 UserAgent。我添加了 httpWebRequest.UserAgent 并且有效。此错误从未在 WebException.

中显示