我们正在使用 Web API 为我们的应用程序提供 RESTful 服务,该应用程序目前正在使用 WPF,因此需要服务客户端。
我们遇到的问题是,当响应大小超过 64k 时,基础流停止在 64k 并在请求更多数据时抛出异常,尽管 ContentLength 更大(在测试用例中约为 125k)
这是我们调用服务的方法:
private HttpWebResponse CallServiceMethod<TDto>(Uri serviceURL, string method, out WebException requestExceptionDetail, TDto dto = null) where TDto : DTOBase
{
HttpWebRequest request;
HttpWebResponse response;
Encoding enc;
string encodedDto;
byte[] encodedDtoArray;
Stream writeStream;
request = WebRequest.CreateHttp(serviceURL);
request.Method = method;
if (dto != null)
{
enc = UTF8Encoding.Default;
encodedDto = String.Concat("=", JsonConvert.SerializeObject(dto));
encodedDtoArray = enc.GetBytes(encodedDto);
request.ContentLength = encodedDtoArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
writeStream = request.GetRequestStream();
writeStream.Write(encodedDtoArray, 0, encodedDtoArray.Length);
writeStream.Close();
}
requestExceptionDetail = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException wex)
{
response = (HttpWebResponse)wex.Response;
requestExceptionDetail = wex;
}
return response;
}
...这是一种解码响应的方法,中间有一些胶合逻辑可以传递响应。
private TObjectType DecodeResponse<TObjectType>(HttpWebResponse webResponse)
{
Encoding enc;
StreamReader responseReader;
string responseText;
TObjectType retVal;
// Obtain a string from the underlying response string
enc = UTF8Encoding.Default;
responseReader = new StreamReader(webResponse.GetResponseStream(), enc);
responseText = responseReader.ReadToEnd();
// Use JSon to deserialise the string
retVal = JsonConvert.DeserializeObject<TObjectType>(responseText);
return retVal;
}
我们也尝试过这种事情,但无济于事:
private TObjectType DecodeResponse<TObjectType>(HttpWebResponse webResponse)
{
Encoding enc;
StreamReader responseReader;
string responseText;
TObjectType retVal;
char[] buffer;
int bufferSize, startPos, totalLength, readLength;
StringBuilder sbx;
// Obtain a string from the underlying response string
enc = UTF8Encoding.Default;
responseReader = new StreamReader(webResponse.GetResponseStream(), enc);
totalLength = (int)webResponse.ContentLength;
bufferSize = 65536;
startPos = 0;
buffer = new char[bufferSize];
sbx = new StringBuilder(totalLength);
//webResponse.GetResponseStream().
while (startPos < totalLength)
{
readLength = Math.Min(bufferSize, totalLength - startPos);
responseReader.Read(buffer, startPos, readLength);
sbx.Append(buffer, 0, readLength);
startPos += readLength;
}
//responseText = responseReader.ReadToEnd();
responseText = sbx.ToString();
// Use JSon to deserialise the string
retVal = JsonConvert.DeserializeObject<TObjectType>(responseText);
return retVal;
}
任何帮助将非常感激 ;-)