-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpRequestService.cs
More file actions
73 lines (65 loc) · 2.76 KB
/
Copy pathHttpRequestService.cs
File metadata and controls
73 lines (65 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Text.Json;
using Application.Interfaces.Services;
using Domain.Common.Enums;
namespace Application.Services;
public class HttpRequestService(IHttpClientFactory httpClientFactory) : IHttpRequestService
{
public async Task<T> GetAsync<T>(string url, object? data = null, string? token = null)
{
var httpClient = httpClientFactory.CreateClient();
if (!string.IsNullOrEmpty(token))
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
if (data is not null)
{
var query = string.Join("&", data.GetType().GetProperties()
.Select(x =>
$"{Uri.EscapeDataString(x.Name)}={Uri.EscapeDataString(x.GetValue(data)?.ToString() ?? string.Empty)}"));
url += $"?{query}";
}
var response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(content) ??
throw new HttpRequestException(
$"Error deserializing data from the server. Status code: {response.StatusCode}");
}
public async Task<T> PostAsync<T>(string url, object data,
PostRequestMediaType mediaType = PostRequestMediaType.Json)
{
var httpClient = httpClientFactory.CreateClient();
HttpResponseMessage? response = null;
if (mediaType == PostRequestMediaType.Json)
{
var content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");
response = await httpClient.PostAsync(url, content);
}
else if (mediaType == PostRequestMediaType.FormUrlEncoded)
{
var content = new FormUrlEncodedContent(ObjectToKeyValuePairs(data));
response = await httpClient.PostAsync(url, content);
}
response?.EnsureSuccessStatusCode();
var responseContent = await response!.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(responseContent) ??
throw new HttpRequestException(
$"Error deserializing data from the server. Status code: {response.StatusCode}");
}
private static Dictionary<string, string> ObjectToKeyValuePairs(object obj)
{
var keyValuePairs = new Dictionary<string, string>();
foreach (PropertyInfo property in obj.GetType().GetProperties())
{
var value = property.GetValue(obj)?.ToString();
if (value != null)
{
keyValuePairs.Add(property.Name, value);
}
}
return keyValuePairs;
}
}