asp.net WebRequest 流在调试器中抛出 'This stream does not support seek operations' 错误

asp.net WebRequest stream throwing 'This stream does not support seek operations' error in debugger

我是 asp.net 中 WebRequest 调用的新手。我正在尝试将 WebRequest 与 Expedia (EAN) API (https://developer.ean.com/code-library/) 一起使用。他们有一个不起作用的例子(据我所知)并且即使使用他们自己的 API.

也不能帮助编码人员

这是我的问题:

当我在调试器中调用 request.GetRequestStream() 时,我得到了一个 “'((System.Net.ConnectStream)dataStream).Length' 引发了类型为 'System.NotSupportedException' 的异常,值为 "This stream does not support seek operations"。

当然,GetResponse() 调用会超时。

我也不清楚 Web 字符串的哪一部分被发送到 .Create 方法(下面的 xmlpath)以及哪一部分被流式传输到请求(下面的 postData)??

代码如下:

string xmlpath = "http://api.ean.com/ean-services/rs/hotel/v3/avail?";
string postData = "minorRev=99&cid=55505&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&_type=json&hotelId=125719&arrivalDate=11/11/2015&departureDate=11/13/2015&includeDetails=true&includeRoomImages=true&room1=2,5,7";

WebRequest request = WebRequest.Create(xmlpath);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
request.Timeout = 10000;

Stream dataStream = request.GetRequestStream();

dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

WebResponse myResponse = request.GetResponse();

StreamReader reader = new StreamReader(myResponse.GetResponseStream());
string responseFromServer = reader.ReadToEnd();

考虑到它是第 3 方 API,我知道这可能很多,但是有人看到我可能做错了什么吗???

谢谢, -戴夫

如果您查看他们的文档,您会看到:

Services within the EAN API are accessed via this standard base URL format for all protocols

这意味着您需要执行 GET 请求并在 URL 中粘贴搜索参数。所以你的代码可能看起来像这样:

var url =
    "http://api.ean.com/ean-services/rs/hotel/v3/avail" +
    "?minorRev=99&cid=55505&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US" +
    "&currencyCode=USD&_type=json&hotelId=125719&arrivalDate=11/11/2015" +
    "&departureDate=11/13/2015&includeDetails=true" +
    "&includeRoomImages=true&room1=2,5,7";
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";

using (var res = req.GetResponse())
{
    using (var resStream = res.GetResponseStream())
    {
        using (var reader = new StreamReader(resStream))
        {
            var json = reader.ReadToEnd();
        }
    }
}

而且您真的不需要处理所有这些请求、响应和流。如果您使用的是 .Net 4.5,请查看 HttClient。使用此 class 代码将非常短:

using (var httpClient = new HttpClient())
{
    var json = httpClient.GetStringAsync(url).Result;
}