/// <summary>
        /// Parses the JSON into an object of the specified type.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="type">The type.</param>
        /// <param name="jsonSettings">The JSON settings.</param>
        /// <returns>An object of the specified type.</returns>
        /// <exception cref="WebServiceException">The response content does not use the JSON content type, or the content is empty,
        /// or the text is not valid JSON, or the JSON cannot be deserialized into the specified type.</exception>
        /// <remarks>Use JToken as the type to parse arbitrary JSON.</remarks>
        public static async Task <object?> GetJsonAsAsync(this HttpResponseMessage response, Type type, JsonSettings?jsonSettings)
        {
            try
            {
                // StreamReader will throw an ArgumentException when Stream.CanRead is false. It's suspected that this
                // might happen if the HTTP request is canceled (via HttpClient.Timeout) before the response is read.
                var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                if (!responseStream.CanRead)
                {
                    throw HttpResponseMessageUtility.CreateWebServiceException(response, "Response stream is not readable.");
                }

                // parse JSON to desired value
                using var wrappingStream = new WrappingStream(responseStream, Ownership.None);
                using var reader         = new StreamReader(wrappingStream);
                return(JsonUtility.FromJsonTextReader(reader, type, jsonSettings));
            }
            catch (JsonReaderException x)
            {
                // JSON invalid
                throw HttpResponseMessageUtility.CreateWebServiceException(response, "Response is not valid JSON: " + x.Message, x);
            }
            catch (JsonSerializationException x)
            {
                // JSON can't be deserialized
                throw HttpResponseMessageUtility.CreateWebServiceException(response, "Response JSON could not be deserialized to {0}: {1}".FormatInvariant(type, x.Message), x);
            }
        }
        /// <summary>
        /// Gets the JSON.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <returns>The unverified JSON.</returns>
        /// <exception cref="WebServiceException">The response content does not use the JSON content type or the content is empty.</exception>
        public static async Task <string> GetJsonAsync(this HttpResponseMessage response)
        {
            if (!response.HasJson())
            {
                throw await HttpResponseMessageUtility.CreateWebServiceExceptionWithContentPreviewAsync(response, "The response does not have JSON content.").ConfigureAwait(false);
            }

            return(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
        }
 private static Task <WebServiceException> CreateExceptionAsync(WebServiceResponseHandlerInfo info, string message)
 {
     if (info.IsContentRead)
     {
         return(Task.FromResult(HttpResponseMessageUtility.CreateWebServiceException(info.WebResponse, message)));
     }
     else
     {
         info.MarkContentAsRead();
         return(HttpResponseMessageUtility.CreateWebServiceExceptionWithContentPreviewAsync(info.WebResponse, message));
     }
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Called when the response has been handled, i.e. immediately before it is returned.
        /// </summary>
        /// <param name="info">The web service response handler information.</param>
        protected virtual async Task OnResponseHandledCoreAsync(WebServiceResponseHandlerInfo info)
        {
            m_requestMethod         = info.WebResponse !.RequestMessage.Method.Method;
            m_requestUri            = info.WebResponse.RequestMessage.RequestUri;
            m_responseStatusCode    = info.WebResponse.StatusCode;
            m_responseHeaders       = info.WebResponse.Headers;
            m_responseContentType   = info.WebResponse.Content?.Headers?.ContentType?.ToString();
            m_responseContentLength = info.WebResponse.Content?.Headers?.ContentLength;

            if (!info.IsContentRead)
            {
                m_responseContentPreview = await HttpResponseMessageUtility.ReadContentPreviewAsync(info.WebResponse).ConfigureAwait(false);

                info.MarkContentAsRead();
            }
        }
        /// <summary>
        /// Parses the JSON into an object of the specified type.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="type">The type.</param>
        /// <param name="jsonSettings">The JSON settings.</param>
        /// <returns>An object of the specified type.</returns>
        /// <exception cref="WebServiceException">The response content does not use the JSON content type, or the content is empty,
        /// or the text is not valid JSON, or the JSON cannot be deserialized into the specified type.</exception>
        /// <remarks>Use JToken as the type to parse arbitrary JSON.</remarks>
        public static async Task <object> GetJsonAsAsync(this HttpResponseMessage response, Type type, JsonSettings jsonSettings)
        {
            try
            {
                // parse JSON to desired value
                Stream responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                using (WrappingStream wrappingStream = new WrappingStream(responseStream, Ownership.None))
                    using (StreamReader reader = new StreamReader(wrappingStream))
                        return(JsonUtility.FromJsonTextReader(reader, type, jsonSettings));
            }
            catch (JsonReaderException x)
            {
                // JSON invalid
                throw HttpResponseMessageUtility.CreateWebServiceException(response, "Response is not valid JSON: " + x.Message, x);
            }
            catch (JsonSerializationException x)
            {
                // JSON can't be deserialized
                throw HttpResponseMessageUtility.CreateWebServiceException(response, "Response JSON could not be deserialized to {0}: {1}".FormatInvariant(type, x.Message), x);
            }
        }