Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BaseHttpClient
- {
- private readonly HttpClient _httpClient;
- protected BaseHttpClient(HttpClient httpClient)
- {
- _httpClient = httpClient;
- }
- protected async Task<T> Get<T>()
- {
- var request = CreateRequest(HttpMethod.Get, _httpClient.BaseAddress?.ToString());
- return await ExecuteRequest<T>(request);
- }
- private static HttpRequestMessage CreateRequest(HttpMethod httpMethod, string uri, object content = null)
- {
- var request = new HttpRequestMessage(httpMethod, uri);
- if (content == null) return request;
- var json = JsonSerializer.Serialize(content);
- request.Content = new StringContent(json, Encoding.UTF8, "application/json");
- return request;
- }
- private async Task<T> ExecuteRequest<T>(HttpRequestMessage request)
- {
- try
- {
- var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
- .ConfigureAwait(false);
- var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
- var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
- response.EnsureSuccessStatusCode();
- return string.IsNullOrEmpty(responseContent) ? default : JsonSerializer.Deserialize<T>(responseContent, options);
- }
- catch (Exception ex) when (ex is ArgumentNullException ||
- ex is InvalidOperationException ||
- ex is HttpRequestException ||
- ex is JsonException)
- {
- throw new Exception("HttpClient exception", ex);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement