public static SdkResponse <TSuccess, TError> ParseResponse <TSuccess, TError>(IRawResponse response) where TSuccess : class where TError : class { if (response.Body is Exception) { return(new SdkResponse <TSuccess, TError> { Error = response.Body as TError }); } switch (SdkUtils.ResponseMode(response.ContentType)) { case ResponseMode.Binary: return(new SdkResponse <TSuccess, TError> { Value = response.Body as TSuccess }); case ResponseMode.String: if (response.ContentType.StartsWith("application/json")) { return(new SdkResponse <TSuccess, TError> { Value = JsonConvert.DeserializeObject <TSuccess>(response.Body.ToString()) }); } else { return(new SdkResponse <TSuccess, TError> { Value = response.Body.ToString() as TSuccess }); } case ResponseMode.Unknown: return(new SdkResponse <TSuccess, TError> { Error = JsonConvert.DeserializeObject <TError>(response.Body.ToString()) }); default: throw new ArgumentOutOfRangeException($"Unrecognized Content Type {response.ContentType}"); } }
public async Task <IRawResponse> RawRequest( HttpMethod method, string path, Values queryParams = null, object body = null, Authenticator authenticator = null, ITransportSettings options = null ) { var url = MakeUrl(path, queryParams, authenticator); var request = new HttpRequestMessage(method, url); request.Headers.Add(Constants.LookerAppiId, _settings.AgentTag); if (body != null) { if (body is string) { request.Content = new StringContent( body.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded"); } else { request.Content = new StringContent( JsonSerializer.Serialize(body, new JsonSerializerOptions { IgnoreNullValues = true }), Encoding.UTF8, "application/json"); } } if (authenticator != null) { request = await authenticator(request); } RawResponse result = new RawResponse(); HttpResponseMessage response = null; try { response = await _client.SendAsync(request); result = InitRawResponse(response); // if (response.IsSuccessStatusCode) await using var stream = await response.Content.ReadAsStreamAsync(); // Simple content conversion here to make body easily readable in consumers switch (SdkUtils.ResponseMode(result.ContentType)) { case ResponseMode.Binary: result.Body = SdkUtils.StreamToByteArray(stream); break; case ResponseMode.String: using (var sr = new StreamReader(stream)) { result.Body = await sr.ReadToEndAsync(); } break; case ResponseMode.Unknown: result.Body = SdkUtils.StreamToByteArray(stream); break; default: throw new ArgumentOutOfRangeException($"Unrecognized Content Type {result.ContentType}"); } } catch (Exception e) { result = InitRawResponse(response); result.Body = e; } return(result); }