[英]WEBException was unhandled: The remote server returned an error: (500) Internal Server Error
I am implementing REST service and I am getting the above error. 我正在实现REST服务,并且出现上述错误。 I searched a lot and used different methods to resolve this error but no luck.
我进行了大量搜索,并使用了不同的方法来解决此错误,但是没有运气。 The service is working fine when I am using Postman or fiddler.
当我使用邮递员或提琴手时,该服务运行良好。
Here is my code : 这是我的代码:
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;
}
So in the above code I tried with : 所以在上面的代码中,我尝试了:
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
HttpUtility.UrlEncode()
I also tried the below code but it is giving me the same error : 我也尝试了下面的代码,但它给了我同样的错误:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString("https://api.MYDOMAIN.com/servlet/Year", "POST", "{\"securitykey\":\"MYKEY\"}");
}
I added the security key in raw header as httpWebRequest.Headers.Add("{\\"securitykey\\":\\"MYKEY\\"}")
but still no luck. 我在原始标头中将安全密钥添加为
httpWebRequest.Headers.Add("{\\"securitykey\\":\\"MYKEY\\"}")
但还是没有运气。
Really appreciate if I can get some help. 真的很感激,如果我能得到一些帮助。
After a lot of RND I tried doing this in PHP, so it gave me an error as UserAgent is required. 经过大量RND之后,我尝试使用PHP进行此操作,因此由于需要UserAgent,因此给了我一个错误。 I added
httpWebRequest.UserAgent
and it worked. 我添加了
httpWebRequest.UserAgent
,并且有效。 This error was never displayed in WebException
. 此错误从未在
WebException
显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.