在检查响应状态后,将RestSharp响应作为流进行处理?

时间:2015-07-15 23:44:52

标签: c# rest stream restsharp

我必须能够使用RestSharp从Rest API流式传输大型文件。这样做的规范方法是设置' ResponseWriter'物业请求:

var client = new RestClient
var request = new RestRequest();
IRestResponse response;
request.ResponseWriter = connectStream => {
  if(response.StatusCode == ResponseStatus.OK)
  {
     CloudStorage.UploadFromStream(connectStream);
  }
  else
  {
     LoggerService.LogErrorFromStream(connectStream);
  }
};
response = client.Execute(request);

我的问题是'回应'对象(包括状态,状态代码,标题等)在 RestSharp完成后要求我的ResponseWriter处理整个流之后才可用。

这似乎违反直觉,因为用户当然可能希望根据响应状态更改响应流的处理方式。

在开始处理响应主体的流之前,如何获取此状态信息?

2 个答案:

答案 0 :(得分:3)

我认为这已在 here 之前报告。

看起来他们released对此进行了更新,而这样做的方法是改用 AdvancedResponseWriter

var client = new RestClient
var request = new RestRequest();
IRestResponse response;
request.AdvancedResponseWriter = (stream, response) => {
    // Should be able to access response which is an IHttpResponse
};
response = client.Execute(request);

Docs

答案 1 :(得分:-3)

看起来在调用ResponseWriter之前设置了一些头文件,这些头文件在ProcessResponseStream方法中发生,并且之后设置了一些头文件。状态是在调用ResponseWriter之后设置的标头之一。

请参阅代码:RestSharp Http.cs

       private void ExtractResponseData(HttpResponse response, HttpWebResponse webResponse)
        {
            using (webResponse)
            {
#if FRAMEWORK
                response.ContentEncoding = webResponse.ContentEncoding;
                response.Server = webResponse.Server;
                response.ProtocolVersion = webResponse.ProtocolVersion;
#endif
                response.ContentType = webResponse.ContentType;
                response.ContentLength = webResponse.ContentLength;

                Stream webResponseStream = webResponse.GetResponseStream();

#if WINDOWS_PHONE
                if (string.Equals(webResponse.Headers[HttpRequestHeader.ContentEncoding], "gzip", StringComparison.OrdinalIgnoreCase))
                {
                    GZipStream gzStream = new GZipStream(webResponseStream);

                    ProcessResponseStream(gzStream, response);
                }
                else
                {
                    ProcessResponseStream(webResponseStream, response);
                }
#else
                this.ProcessResponseStream(webResponseStream, response);
#endif

                response.StatusCode = webResponse.StatusCode;
                response.StatusDescription = webResponse.StatusDescription;
                response.ResponseUri = webResponse.ResponseUri;
                response.ResponseStatus = ResponseStatus.Completed;