Dispose() public method

public Dispose ( ) : void
return void
        private HttpResponseMessage Execute()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Redirect);

            try
            {
                var sim = _message.Protect(600, _internalConfig.DataProtector);

                if (_loginPageUrl.IsMissing())
                {
                    var urlHelper = _request.GetUrlHelper();
                    _loginPageUrl = urlHelper.Route(Constants.RouteNames.Login, new { message = sim });
                }
                else
                {
                    _loginPageUrl += "?message=" + sim;
                }

                var uri = new Uri(_request.RequestUri, _loginPageUrl);

                response.Headers.Location = uri;
            }
            catch
            {
                response.Dispose();
                throw;
            }

            Logger.Info("Redirecting to login page");
            return response;
        }
        private HttpResponseMessage Execute()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Redirect);

            try
            {
                var protection = _settings.GetInternalProtectionSettings();
                var jwt = _message.ToJwt(
                    protection.Issuer,
                    protection.Audience,
                    protection.SigningKey,
                    protection.Ttl);

                var urlHelper = _request.GetUrlHelper();
                var loginUrl = urlHelper.Route(Constants.RouteNames.Login, new { message = jwt });
                var uri = new Uri(_request.RequestUri, loginUrl);

                response.Headers.Location = uri;
            }
            catch
            {
                response.Dispose();
                throw;
            }

            return response;
        }
Example #3
0
        public override Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            ContentNegotiationResult result = GetContentNegotiationResult();

            HttpResponseMessage response = null;
            try
            {
                response = new HttpResponseMessage();

                if (result == null)
                {
                    //TODO: find condtions when this case can be reached
                    // A null result from content negotiation indicates that the response should be a 406.
                    response.StatusCode = HttpStatusCode.NotAcceptable;
                }
                else
                {
                    response.StatusCode = HttpStatusCode.OK;
                    response.Content = new ObjectContent<object>(new object(), result.Formatter, result.MediaType);
                }

                response.RequestMessage = Request;
            }
            catch
            {
                if (response != null)
                {
                    response.Dispose();
                }

                throw;
            }

            return Task.FromResult(response);
        }
        internal static HttpResponseMessage Execute(HttpStatusCode statusCode, HttpRequestMessage request)
        {
            HttpResponseMessage response = new HttpResponseMessage(statusCode);

            try
            {
                response.RequestMessage = request;
            }
            catch
            {
                response.Dispose();
                throw;
            }

            return response;
        }
        private HttpResponseMessage Execute()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Redirect);

            try
            {
                response.Headers.Location = _location;
                response.RequestMessage = _dependencies.Request;
            }
            catch
            {
                response.Dispose();
                throw;
            }

            return response;
        }
        private HttpResponseMessage Execute()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);

            try
            {
                foreach (AuthenticationHeaderValue challenge in _challenges)
                {
                    response.Headers.WwwAuthenticate.Add(challenge);
                }

                response.RequestMessage = _dependencies.Request;
            }
            catch
            {
                response.Dispose();
                throw;
            }

            return response;
        }
        private HttpResponseMessage Execute()
        {
            var response = new HttpResponseMessage(HttpStatusCode.Redirect);

            try
            {
                var sim = _message.Protect(600, _protector);
                var url = _env.GetIdentityServerBaseUrl() + Constants.RoutePaths.Login;
                url += "?message=" + sim;

                var uri = new Uri(url);
                response.Headers.Location = uri;
            }
            catch
            {
                response.Dispose();
                throw;
            }

            Logger.Info("Redirecting to login page");
            return response;
        }
        private HttpResponseMessage Execute()
        {
            HttpResponseMessage mutableResponse = new HttpResponseMessage(_statusCode);
            HttpResponseMessage response = null;

            try
            {
                mutableResponse.RequestMessage = _dependencies.Request;

                response = mutableResponse;
                mutableResponse = null;
            }
            finally
            {
                if (mutableResponse != null)
                {
                    mutableResponse.Dispose();
                }
            }

            return response;
        }
        private HttpResponseMessage Execute()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Redirect);

            try
            {
                var sim = _message.Protect(60, _internalConfig.DataProtector);

                var urlHelper = _request.GetUrlHelper();
                var loginUrl = urlHelper.Route(Constants.RouteNames.Login, new { message = sim });
                var uri = new Uri(_request.RequestUri, loginUrl);

                response.Headers.Location = uri;
            }
            catch
            {
                response.Dispose();
                throw;
            }

            return response;
        }
        /// <summary>
        /// Converts a <see cref="HttpResponseMessage"/> to an <see cref="HttpResponseBase"/> and disposes the 
        /// <see cref="HttpResponseMessage"/> and <see cref="HttpRequestMessage"/> upon completion.
        /// </summary>
        /// <param name="httpContextBase">The HTTP context base.</param>
        /// <param name="response">The response to convert.</param>
        /// <param name="request">The request (which will be disposed).</param>
        /// <returns>A <see cref="Task"/> representing the conversion of an <see cref="HttpResponseMessage"/> to an <see cref="HttpResponseBase"/>
        /// including writing out any entity body.</returns>
        internal static Task ConvertResponse(HttpContextBase httpContextBase, HttpResponseMessage response, HttpRequestMessage request)
        {
            Contract.Assert(httpContextBase != null);
            Contract.Assert(response != null);
            Contract.Assert(request != null);

            HttpResponseBase httpResponseBase = httpContextBase.Response;
            httpResponseBase.StatusCode = (int)response.StatusCode;
            httpResponseBase.StatusDescription = response.ReasonPhrase;
            httpResponseBase.TrySkipIisCustomErrors = true;
            EnsureSuppressFormsAuthenticationRedirect(httpContextBase);
            CopyHeaders(response.Headers, httpContextBase);
            CacheControlHeaderValue cacheControl = response.Headers.CacheControl;

            // TODO 335085: Consider this when coming up with our caching story
            if (cacheControl == null)
            {
                // DevDiv2 #332323. ASP.NET by default always emits a cache-control: private header.
                // However, we don't want requests to be cached by default.
                // If nobody set an explicit CacheControl then explicitly set to no-cache to override the
                // default behavior. This will cause the following response headers to be emitted:
                //     Cache-Control: no-cache
                //     Pragma: no-cache
                //     Expires: -1
                httpContextBase.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }

            Task responseTask = null;
            bool isBuffered = false;

            if (response.Content != null)
            {
                CopyHeaders(response.Content.Headers, httpContextBase);

                // Select output buffering by the kind of content
                isBuffered = IsOutputBufferingNecessary(response.Content);
                httpResponseBase.BufferOutput = isBuffered;

                responseTask = response.Content.CopyToAsync(httpResponseBase.OutputStream);
            }
            else
            {
                responseTask = TaskHelpers.Completed();
            }

            return responseTask
                .Catch((info) =>
                {
                    if (isBuffered)
                    {
                        // Failure during the CopyToAsync needs to stop any partial content from
                        // reaching the client.  If it was during a buffered write, we will give
                        // them InternalServerError with zero-length content.
                        httpResponseBase.SuppressContent = true;
                        httpResponseBase.Clear();
                        httpResponseBase.ClearContent();
                        httpResponseBase.ClearHeaders();
                        httpResponseBase.StatusCode = (int)Net.HttpStatusCode.InternalServerError;
                    }
                    else
                    {
                        // Any failure in non-buffered mode has already written out StatusCode and possibly content.
                        // This means the client will receive an OK but the content is incomplete.
                        // The proper action here is to abort the connection, but HttpResponse.Abort is a 4.5 feature.
                        // TODO: DevDiv bug #381233 -- call HttpResponse.Abort when it becomes available
                        httpResponseBase.Close();
                    }

                    // We do not propagate any errors up, or we will get the
                    // standard ASP.NET html page.   We want empty content or
                    // a closed connection.
                    return info.Handled();
                })
                .Finally(
                () =>
                {
                    request.DisposeRequestResources();
                    request.Dispose();
                    response.Dispose();
                });
        }
 private static async Task<HttpResponseMessage> BufferResponseBodyAsync(HttpRequestMessage request, HttpResponseMessage response)
 {
     try
     {
         await response.Content.LoadIntoBufferAsync();
         return response;
     }
     catch (Exception exception)
     {
         response.Dispose();
         return request.CreateErrorResponse(HttpStatusCode.InternalServerError, exception);
     }
 }
 private static async Task CreateErrorResponseAsyncCore(HttpResponseMessage errorResponse, HttpResponseBase httpResponseBase)
 {
     try
     {
         // Asynchronously write the content of the new error HttpResponseMessage
         await errorResponse.Content.CopyToAsync(httpResponseBase.OutputStream);
     }
     catch
     {
         // Failure writing the error response.  Likely cause is a formatter
         // serialization exception.  Create empty error response and
         // return a non-faulted task.
         CreateEmptyErrorResponse(httpResponseBase);
     }
     finally
     {
         // Dispose the temporary HttpResponseMessage carrying the error response
         errorResponse.Dispose();
     }
 }
        /// <summary>
        /// Converts a <see cref="HttpResponseMessage"/> to an <see cref="HttpResponseBase"/> and disposes the 
        /// <see cref="HttpResponseMessage"/> and <see cref="HttpRequestMessage"/> upon completion.
        /// </summary>
        /// <param name="httpContextBase">The HTTP context base.</param>
        /// <param name="response">The response to convert.</param>
        /// <param name="request">The request (which will be disposed).</param>
        /// <returns>A <see cref="Task"/> representing the conversion of an <see cref="HttpResponseMessage"/> to an <see cref="HttpResponseBase"/>
        /// including writing out any entity body.</returns>
        internal static async Task ConvertResponse(HttpContextBase httpContextBase, HttpResponseMessage response, HttpRequestMessage request)
        {
            Contract.Assert(httpContextBase != null);
            Contract.Assert(request != null);

            // A null response creates a 500 with no content
            if (response == null)
            {
                CreateEmptyErrorResponse(httpContextBase.Response);
                return;
            }

            CopyResponseStatusAndHeaders(httpContextBase, response);

            // TODO 335085: Consider this when coming up with our caching story
            if (response.Headers.CacheControl == null)
            {
                // DevDiv2 #332323. ASP.NET by default always emits a cache-control: private header.
                // However, we don't want requests to be cached by default.
                // If nobody set an explicit CacheControl then explicitly set to no-cache to override the
                // default behavior. This will cause the following response headers to be emitted:
                //     Cache-Control: no-cache
                //     Pragma: no-cache
                //     Expires: -1
                httpContextBase.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }

            // Asynchronously write the response body.  If there is no body, we use
            // a completed task to share the Finally() below.
            // The response-writing task will not fault -- it handles errors internally.
            try
            {
                if (response.Content != null)
                {
                    await WriteResponseContentAsync(httpContextBase, response, request);
                }
            }
            finally
            {
                request.DisposeRequestResources();
                request.Dispose();
                response.Dispose();
            }
        }
        private HttpResponseMessage Execute()
        {
            var httpResponseMessage = new HttpResponseMessage();

            try
            {
                var negotiationResult = ContentNegotiator.Negotiate(typeof(HttpError), Request, Formatters);

                if (negotiationResult == null)
                {
                    httpResponseMessage.StatusCode = HttpStatusCode.NotAcceptable;
                }
                else
                {
                    var error = new HttpError("Internal Server Error");
                    foreach (var property in Exception.GetCustomProperties())
                    {
                        error.Add(property.Key, property.Value);
                    }

                    httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
                    httpResponseMessage.Content = new ObjectContent<HttpError>(error, negotiationResult.Formatter, negotiationResult.MediaType);
                }

                httpResponseMessage.RequestMessage = Request;
            }
            catch
            {
                httpResponseMessage.Dispose();
                throw;
            }

            return httpResponseMessage;
        }
        private HttpResponseMessage Execute()
        {
            var httpResponseMessage = new HttpResponseMessage();

            try
            {
                var negotiationResult = ContentNegotiator.Negotiate(typeof(HttpError), Request, Formatters);

                if (negotiationResult == null)
                {
                    httpResponseMessage.StatusCode = HttpStatusCode.NotAcceptable;
                }
                else
                {
                    var error = new HttpError("Validation Failed");
                    foreach (var err in _exception.ValidationErrors)
                    {
                        if (!error.ContainsKey(err.ItemName))
                        {
                            error.Add(err.ItemName, new Collection<ApiError>());
                        }

                        ((ICollection<ApiError>)error[err.ItemName]).Add(new ApiError
                        {
                            ErrorCode = err.ErrorCode,
                            Message = err.ErrorMessage
                        });
                    }

                    httpResponseMessage.StatusCode = HttpStatusCode.BadRequest;
                    httpResponseMessage.Content = new ObjectContent<HttpError>(error, negotiationResult.Formatter, negotiationResult.MediaType);
                }

                httpResponseMessage.RequestMessage = Request;
            }
            catch
            {
                httpResponseMessage.Dispose();
                throw;
            }

            return httpResponseMessage;
        }
Example #16
0
            /// <summary>
            /// Send a GET request to the specified Uri as an asynchronous operation.
            /// </summary>
            /// <returns>A task for the asynchronous operation.</returns>
            /// <seealso cref="IHttpClient.SendGetRequest"/>
            public Task<HttpResponseMessage> SendGetRequest()
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                Stream resourceStream = assembly.GetManifestResourceStream(this._resourceName);

                Task<HttpResponseMessage> returnTask;
                try
                {
                    HttpResponseMessage response = new HttpResponseMessage();

                    try
                    {
                        response.StatusCode = HttpStatusCode.OK;
                        response.Content = new StreamContent(resourceStream);

                        returnTask = TaskExt.WrapInTask(() => response);
                    }
                    catch
                    {
                        response.Dispose();
                        throw;
                    }
                }
                catch
                {
                    resourceStream.Dispose();
                    throw;
                }

                return returnTask;
            }
Example #17
0
        // only valid response codes are 500 (if it's a fault) or 200 (iff it's a response message)
        public static HttpInput ValidateRequestReplyResponse(HttpRequestMessage request, HttpResponseMessage response,
          HttpChannelFactory<IRequestChannel> factory, HttpRequestException responseException)
        {
            ValidateAuthentication(request, response, responseException, factory);

            HttpInput httpInput = null;

            // We will close the HttpResponseMessage if we got an error code betwen 200 and 300 and 
            // 1) an exception was thrown out or 
            // 2) it's an empty message and we are using SOAP.
            // For responses with status code above 300, System.Net will close the underlying connection so we don't need to worry about that.
            if ((200 <= (int)response.StatusCode && (int)response.StatusCode < 300) || response.StatusCode == HttpStatusCode.InternalServerError)
            {
                if (response.StatusCode == HttpStatusCode.InternalServerError
                    && string.Compare(response.ReasonPhrase, HttpChannelUtilities.StatusDescriptionStrings.HttpStatusServiceActivationException, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ServiceActivationException(SR.Format(SR.Hosting_ServiceActivationFailed, request.RequestUri)));
                }
                else
                {
                    bool throwing = true;
                    try
                    {
                        string contentType = GetContentTypeString(response);
                        long contentLength = GetContentLength(response);
                        if (string.IsNullOrEmpty(contentType))
                        {
                            if (!ValidateEmptyContent(response))
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TraceResponseException(
                                    new ProtocolException(
                                        SR.HttpContentTypeHeaderRequired,
                                        responseException)));
                            }
                        }
                        else if (contentLength != 0)
                        {
                            MessageEncoder encoder = factory.MessageEncoderFactory.Encoder;
                            if (!encoder.IsContentTypeSupported(contentType))
                            {
                                int bytesRead;
                                String responseExcerpt = GetResponseStreamString(response, out bytesRead);

                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TraceResponseException(
                                    new ProtocolException(
                                        SR.Format(
                                            SR.ResponseContentTypeMismatch,
                                            contentType,
                                            encoder.ContentType,
                                            bytesRead,
                                            responseExcerpt), responseException)));
                            }

                            httpInput = HttpInput.CreateHttpInput(response, factory);
                            httpInput.HttpRequestException = responseException;
                        }

                        throwing = false;
                    }
                    finally
                    {
                        if (throwing)
                        {
                            response.Dispose();
                        }
                    }
                }

                if (httpInput == null)
                {
                    if (factory.MessageEncoderFactory.MessageVersion == MessageVersion.None)
                    {
                        httpInput = HttpInput.CreateHttpInput(response, factory);
                        httpInput.HttpRequestException = responseException;
                    }
                    else
                    {
                        // In this case, we got a response with
                        // 1) status code between 200 and 300
                        // 2) Non-empty Content Type string
                        // 3) Zero content length
                        // Since we are trying to use SOAP here, the message seems to be malicious and we should
                        // just close the response directly.
                        response.Dispose();
                    }
                }
            }
            else
            {
                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(SR.Format(SR.EndpointNotFound, request.RequestUri.AbsoluteUri), responseException));
                }

                if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ServerTooBusyException(SR.Format(SR.HttpServerTooBusy, request.RequestUri.AbsoluteUri), responseException));
                }

                if (response.StatusCode == HttpStatusCode.UnsupportedMediaType)
                {
                    string statusDescription = response.ReasonPhrase;
                    if (!string.IsNullOrEmpty(statusDescription))
                    {
                        if (string.Compare(statusDescription, HttpChannelUtilities.StatusDescriptionStrings.HttpContentTypeMissing, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.Format(SR.MissingContentType, request.RequestUri), responseException));
                        }
                    }
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.Format(SR.FramingContentTypeMismatch, request.Content.Headers.ContentType.ToString(), request.RequestUri), responseException));
                }

                if (response.StatusCode == HttpStatusCode.GatewayTimeout)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(response.StatusCode + " " + response.ReasonPhrase, responseException));
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedResponseException(responseException, response));
            }

            return httpInput;
        }
Example #18
0
        private static async Task<dynamic> PackageResult(HttpResponseMessage response)
        {
            if (!response.IsSuccessStatusCode)
            {
                throw new DynamicRestClientResponseException(response);
            }

            var content = await response.Content.ReadAsStringAsync();

            // we squirrel away the request uri so that we can get subsequent pages later
            dynamic d = JsonConvert.DeserializeObject<ExpandoObject>(content);
            if (d.page != null)
            {
                d.page.uri = response.RequestMessage.RequestUri;
            }
            response.Dispose();
            return d;
        }
Example #19
0
 private void ConsumeAndDisposeResponse(HttpResponseMessage response)
 {
     response.Dispose();
 }
        private async Task<HttpResponseMessage> BufferResponseContentAsync(HttpRequestMessage request,
            HttpResponseMessage response, CancellationToken cancellationToken)
        {
            ExceptionDispatchInfo exceptionInfo;

            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                await response.Content.LoadIntoBufferAsync();
                return response;
            }
            catch (Exception exception)
            {
                exceptionInfo = ExceptionDispatchInfo.Capture(exception);
            }

            // If the content can't be buffered, create a buffered error response for the exception
            // This code will commonly run when a formatter throws during the process of serialization

            Debug.Assert(exceptionInfo.SourceException != null);

            ExceptionContext exceptionContext = new ExceptionContext(exceptionInfo.SourceException,
                OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferContent, request, response);

            await _exceptionLogger.LogAsync(exceptionContext, cancellationToken);
            HttpResponseMessage errorResponse = await _exceptionHandler.HandleAsync(exceptionContext,
                cancellationToken);

            response.Dispose();

            if (errorResponse == null)
            {
                exceptionInfo.Throw();
                return null;
            }

            // We have an error response to try to buffer and send back.

            response = errorResponse;
            cancellationToken.ThrowIfCancellationRequested();

            Exception errorException;

            try
            {
                // Try to buffer the error response and send it back.
                await response.Content.LoadIntoBufferAsync();
                return response;
            }
            catch (Exception exception)
            {
                errorException = exception;
            }

            // We tried to send back an error response with content, but we couldn't. It's an edge case; the best we
            // can do is to log that exception and send back an empty 500.

            ExceptionContext errorExceptionContext = new ExceptionContext(errorException,
                OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferError, request, response);
            await _exceptionLogger.LogAsync(errorExceptionContext, cancellationToken);

            response.Dispose();
            return request.CreateResponse(HttpStatusCode.InternalServerError);
        }
        private HttpResponseMessage Execute()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Redirect);

            try
            {
                string link = _dependencies.UrlFactory.Link(_routeName, _routeValues);

                if (link == null)
                {
                    throw new InvalidOperationException(SRResources.UrlHelper_LinkMustNotReturnNull);
                }

                response.Headers.Location = new Uri(link);
                response.RequestMessage = _dependencies.Request;
            }
            catch
            {
                response.Dispose();
                throw;
            }

            return response;
        }
        private static async Task WriteErrorResponseContentAsync(HttpResponseBase httpResponseBase,
            HttpRequestMessage request, HttpResponseMessage errorResponse, CancellationToken cancellationToken,
            IExceptionLogger exceptionLogger)
        {
            HttpRequestMessage ignoreUnused = request;

            try
            {
                Exception exception = null;
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    // Asynchronously write the content of the new error HttpResponseMessage
                    await errorResponse.Content.CopyToAsync(httpResponseBase.OutputStream);
                    return;
                }
                catch (Exception ex)
                {
                    exception = ex;
                }

                Contract.Assert(exception != null);

                ExceptionContext exceptionContext = new ExceptionContext(exception,
                    WebHostExceptionCatchBlocks.HttpControllerHandlerBufferError, request, errorResponse);
                await exceptionLogger.LogAsync(exceptionContext, cancellationToken);

                // Failure writing the error response.  Likely cause is a formatter
                // serialization exception.  Create empty error response and
                // return a non-faulted task.
                SetEmptyErrorResponse(httpResponseBase);
            }
            finally
            {
                // Dispose the temporary HttpResponseMessage carrying the error response
                errorResponse.Dispose();
            }
        }
        public void Dispose_DisposesODataBatchResponseItems()
        {
            MockHttpResponseMessage[] responses = new MockHttpResponseMessage[]
            {
                new MockHttpResponseMessage(),
                new MockHttpResponseMessage(),
                new MockHttpResponseMessage()
            };
            ODataBatchContent batchContent = new ODataBatchContent(new ODataBatchResponseItem[]
            {
                new OperationResponseItem(responses[0]),
                new ChangeSetResponseItem(new HttpResponseMessage[]
                {
                    responses[1],
                    responses[2]
                })
            });
            HttpResponseMessage batchResponse = new HttpResponseMessage
            {
                Content = batchContent
            };

            batchResponse.Dispose();

            foreach (var response in responses)
            {
                Assert.True(response.IsDisposed);
            }
        }
 public void RespondWithResult(object result, Exception error, HttpResponseMessage response)
 {
     Log.D(Tag + ".RespondWithREsult", "Firing Completed event.");
     OnEvent(_complete, result, error);
     if (response != null) {
         response.Dispose();
     }
 }
        private bool ResponseFailed(HttpResponseMessage response)
        {
            var status = response.StatusCode;
            if ((Int32)status >= 300) {
                if (RetryIfFailedPost(status)) {
                    return true;
                }
   
                RetryOrStopIfNecessary(status);
                response.Dispose();
                return true;
            }

            return false;
        }
        private static async Task<HttpResponseMessage> BufferResponseBodyAsync(HttpRequestMessage request, HttpResponseMessage response)
        {
            Exception exception = null;
            try
            {
                await response.Content.LoadIntoBufferAsync();
            }
            catch (Exception e)
            {
                exception = e;
            }

            // If the content can't be buffered, create a buffered error response for the exception
            // This code will commonly run when a formatter throws during the process of serialization
            if (exception != null)
            {
                response.Dispose();
                response = request.CreateErrorResponse(HttpStatusCode.InternalServerError, exception);
                await response.Content.LoadIntoBufferAsync();
            }
            return response;
        }
 private void RespondWithResult(object result, Exception error, HttpResponseMessage response)
 {
     Log.To.Sync.V(Tag, "{0} finished loading ({1} documents)", this, _docCount);
     OnEvent(_complete, result, error);
     if (response != null) {
         response.Dispose();
     }
 }