Advertisement
Hulkstance

Untitled

Oct 5th, 2022
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | None | 0 0
  1. public class BaseHttpClient
  2.     {
  3.         private readonly HttpClient _httpClient;
  4.  
  5.         protected BaseHttpClient(HttpClient httpClient)
  6.         {
  7.             _httpClient = httpClient;
  8.         }
  9.         protected async Task<T> Get<T>()
  10.         {
  11.             var request = CreateRequest(HttpMethod.Get, _httpClient.BaseAddress?.ToString());
  12.  
  13.             return await ExecuteRequest<T>(request);
  14.         }
  15.         private static HttpRequestMessage CreateRequest(HttpMethod httpMethod, string uri, object content = null)
  16.         {
  17.             var request = new HttpRequestMessage(httpMethod, uri);
  18.             if (content == null) return request;
  19.  
  20.  
  21.             var json = JsonSerializer.Serialize(content);
  22.  
  23.             request.Content = new StringContent(json, Encoding.UTF8, "application/json");
  24.  
  25.             return request;
  26.         }
  27.         private async Task<T> ExecuteRequest<T>(HttpRequestMessage request)
  28.         {
  29.             try
  30.             {
  31.                 var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
  32.                     .ConfigureAwait(false);
  33.                 var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  34.  
  35.                 var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
  36.  
  37.                 response.EnsureSuccessStatusCode();
  38.  
  39.                 return string.IsNullOrEmpty(responseContent) ? default : JsonSerializer.Deserialize<T>(responseContent, options);
  40.             }
  41.             catch (Exception ex) when (ex is ArgumentNullException ||
  42.                                        ex is InvalidOperationException ||
  43.                                        ex is HttpRequestException ||
  44.                                        ex is JsonException)
  45.             {
  46.                 throw new Exception("HttpClient exception", ex);
  47.             }
  48.         }
  49.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement