简体   繁体   中英

Translating HttpClient generic code to RestSharp

I'm trying to convert the HttpClient code to RestSharp but unsuccessfully. My attempt is below.

  • I'm not sure whether HttpClient's request.Content can be translated to request.AddStringBody
  • There is a compile time error at this line response.Headers.ToDictionary(a => a.Key, a => a.Value)
private async Task<T> SendAsync<T>(string requestUri, Method method, object? content = null)
{
    var request = new RestRequest($"{_baseUrl}{requestUri}", method);

    if (content is not null)
    {
        request.AddStringBody(JsonSerializer.Serialize(content), DataFormat.Json);
    }

    if (!string.IsNullOrWhiteSpace(_apiKey))
    {
        request.AddHeader("X-MBX-APIKEY", _apiKey);
    }

    var response = await _restClient.ExecuteAsync(request);

    if (response.StatusCode == HttpStatusCode.OK)
    {
        var jsonString = response.Content;

        try
        {
            var data = JsonSerializer.Deserialize<T>(jsonString!);
            return data!;
        }
        catch (JsonException ex)
        {
            var clientException = new BinanceClientException($"Failed to map server response from '${requestUri}' to given type", -1, ex)
            {
                StatusCode = (int)response.StatusCode,
                Headers = response.Headers.ToDictionary(a => a.Key, a => a.Value)
            };

            throw clientException;
        }
    }

    BinanceHttpException? httpException;
    var contentString = response.Content;
    var statusCode = (int)response.StatusCode;
    if (statusCode is >= 400 and < 500)
    {
        if (string.IsNullOrWhiteSpace(contentString))
        {
            httpException = new BinanceClientException("Unsuccessful response with no content", -1);
        }
        else
        {
            try
            {
                httpException = JsonSerializer.Deserialize<BinanceClientException>(contentString);
            }
            catch (JsonException ex)
            {
                httpException = new BinanceClientException(contentString, -1, ex);
            }
        }
    }
    else
    {
        httpException = new BinanceServerException(contentString!);
    }

    httpException.StatusCode = statusCode;
    httpException.Headers = response.Headers.ToDictionary(a => a.Key, a => a.Value);

    throw httpException;
}

HttpClient

private async Task<T> SendAsync<T>(string requestUri, HttpMethod httpMethod, object content = null)
{
    using (var request = new HttpRequestMessage(httpMethod, this.baseUrl + requestUri))
    {
        if (!(content is null))
        {
            request.Content = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");
        }

        if (!(this.apiKey is null))
        {
            request.Headers.Add("X-MBX-APIKEY", this.apiKey);
        }

        HttpResponseMessage response = await this.httpClient.SendAsync(request);

        if (response.IsSuccessStatusCode)
        {
            using (HttpContent responseContent = response.Content)
            {
                string jsonString = await responseContent.ReadAsStringAsync();

                if (typeof(T) == typeof(string))
                {
                    return (T)(object)jsonString;
                }
                else
                {
                    try
                    {
                        T data = JsonConvert.DeserializeObject<T>(jsonString);

                        return data;
                    }
                    catch (JsonReaderException ex)
                    {
                        var clientException = new BinanceClientException($"Failed to map server response from '${requestUri}' to given type", -1, ex);

                        clientException.StatusCode = (int)response.StatusCode;
                        clientException.Headers = response.Headers.ToDictionary(a => a.Key, a => a.Value);

                        throw clientException;
                    }
                }
            }
        }
        else
        {
            using (HttpContent responseContent = response.Content)
            {
                BinanceHttpException httpException = null;
                string contentString = await responseContent.ReadAsStringAsync();
                int statusCode = (int)response.StatusCode;
                if (400 <= statusCode && statusCode < 500)
                {
                    if (string.IsNullOrWhiteSpace(contentString))
                    {
                        httpException = new BinanceClientException("Unsuccessful response with no content", -1);
                    }
                    else
                    {
                        try
                        {
                            httpException = JsonConvert.DeserializeObject<BinanceClientException>(contentString);
                        }
                        catch (JsonReaderException ex)
                        {
                            httpException = new BinanceClientException(contentString, -1, ex);
                        }
                    }
                }
                else
                {
                    httpException = new BinanceServerException(contentString);
                }

                httpException.StatusCode = statusCode;
                httpException.Headers = response.Headers.ToDictionary(a => a.Key, a => a.Value);

                throw httpException;
            }
        }
    }
}

Well, have you checked what are the properties of HeaderParameter are? It's Name , not Key . In addition, you have loads of redundant code:

var request = new RestRequest($"{_baseUrl}{requestUri}", method);

if (content is not null)
{
    request.AddJsonBody(content);
}

if (!string.IsNullOrWhiteSpace(_apiKey))
{
    request.AddHeader("X-MBX-APIKEY", _apiKey);
}

var response = await _restClient.ExecuteAsync<T>(request);

if (response.StatusCode == HttpStatusCode.OK && response.Data != null)
{
    return response.Data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM