HttpWebRequest提供500状态代码,但是从API返回JSON?

时间:2017-01-28 00:26:38

标签: c# asp.net-web-api httpwebrequest httpwebresponse http-status-code-500

问题背景:

我正在尝试对我在Azure中托管的Web API进行简单的let data = new Uint8Array(req.files.image.data); lwip.open(data, { width: parseInt(req.body.width), height: parseInt(req.body.height) }, (image, err) => ...)

问题:

如果我通过浏览器或Postman等请求工具访问我的Web API端点,我收到HttpWebRequest响应但没有问题。

如果我尝试通过JSON调用访问同一个端点,我会收到500致命错误,但我能够在HttpWebRequest的响应属性中看到Try Catch响应已被退回。

JSON

守则:

以下是我对Web API的简单请求。如前所述,在The remote server returned an error: (500) Internal Server Error. 中,回复 返回我期望的Catch,如下所示:

JSON

请求:

{"ResponseMessage":"OK","ResponseContent:[{"kind":"youtube#playlistItem","etag":"\"gMxXHe- ........ etc }]}

我很欣赏确定500的原因不是直截了当的,但任何人都可以提供一个理由我会收到此错误,但仍然从服务中收到 string url ="http://myapi.azurewebsites.net/api/videos/GetYouTubeVideos"; try { HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest; WebResponse wr = req.GetResponse(); } catch (WebException wex) { var pageContent = new StreamReader(wex.Response.GetResponseStream()) .ReadToEnd(); } 显然是例外吗

1 个答案:

答案 0 :(得分:0)

有一些关于WebHeaders的属性你必须小心!示例代码:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "GET";
webRequest.Proxy = webProxy;
webRequest.AllowAutoRedirect = true;
webRequest.Timeout = 20 * 1000;
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36";
WebResponse wr = webRequest.GetResponse()