-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJsonClient.cs
More file actions
92 lines (74 loc) · 2.75 KB
/
Copy pathJsonClient.cs
File metadata and controls
92 lines (74 loc) · 2.75 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System.Net;
using System.Net.Http.Headers;
using System.Text.Json;
namespace BlazorDemo.Shared.Data;
public class JsonClient : IDisposable
{
public enum ClientConfiguration
{
WebApi,
Unauthenticated
}
protected readonly HttpClient HttpClient;
// ReSharper disable once MemberCanBeProtected.Global
public JsonClient(IHttpClientFactory factory,
ClientConfiguration configuration = ClientConfiguration.WebApi)
{
HttpClient = factory.CreateClient(configuration.ToString());
HttpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<string> PostAsync(string url, HttpContent content)
{
var responseMessage = await HttpClient.PostAsync(url, content);
return await VerifySuccessAsync(responseMessage);
}
public async Task<string> GetAsync(string url)
{
var responseMessage = await HttpClient.GetAsync(url);
return await VerifySuccessAsync(responseMessage);
}
public async Task<string> PutAsync(string url, HttpContent content)
{
var responseMessage = await HttpClient.PutAsync(url, content);
return await VerifySuccessAsync(responseMessage);
}
protected async Task<T?> PostAsync<T>(string url, HttpContent content)
{
return JsonSerializer.Deserialize<T>(await PostAsync(url, content));
}
protected async Task<T?> PutAsync<T>(string url, HttpContent content)
{
return JsonSerializer.Deserialize<T>(await PutAsync(url, content));
}
protected async Task<T?> GetAsync<T>(string url)
{
return JsonSerializer.Deserialize<T>(await GetAsync(url));
}
protected async Task<bool> DeleteAsync(string url)
{
var responseMessage = await HttpClient.DeleteAsync(url);
return responseMessage.IsSuccessStatusCode;
}
private static async Task<string> VerifySuccessAsync(HttpResponseMessage responseMessage)
{
if (responseMessage.Content == null) throw new SimpleHttpResponseException(responseMessage.StatusCode, "No content");
var content = await responseMessage.Content.ReadAsStringAsync();
if (responseMessage.IsSuccessStatusCode) return content;
responseMessage.Content.Dispose();
throw new SimpleHttpResponseException(responseMessage.StatusCode, content);
}
public void Dispose()
{
HttpClient.Dispose();
GC.SuppressFinalize(this);
}
}
public class SimpleHttpResponseException : Exception
{
public HttpStatusCode StatusCode { get; }
public SimpleHttpResponseException(HttpStatusCode statusCode, string content) : base(content)
{
StatusCode = statusCode;
}
}