-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequest.cs
More file actions
539 lines (452 loc) · 14.3 KB
/
Copy pathRequest.cs
File metadata and controls
539 lines (452 loc) · 14.3 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
using FrApp42.Web.API.Helpers;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
using System.Xml.Serialization;
namespace FrApp42.Web.API
{
public class Request
{
#region Variables
/// <summary>
/// The HTTP client used to send requests.
/// </summary>
private readonly HttpClient _httpClient = new();
/// <summary>
/// Gets or sets the timeout applied to every request sent by this instance.
/// Defaults to 100 seconds (HttpClient default).
/// Set to <see cref="System.Threading.Timeout.InfiniteTimeSpan"/> to disable.
/// </summary>
public TimeSpan Timeout
{
get => _httpClient.Timeout;
set => _httpClient.Timeout = value;
}
/// <summary>
/// Settings for JSON serialization.
/// </summary>
private readonly JsonSerializerSettings _jsonSerializerSettings = new()
{
ContractResolver = new JsonPropAttrResolver(),
Formatting = Formatting.Indented
};
/// <summary>
/// Set body as JSON
/// </summary>
private bool _isJsonBody = false;
/// <summary>
/// Gets the URL to send the request to.
/// </summary>
public string URL { get; private set; } = string.Empty;
/// <summary>
/// Gets the HTTP method to use for the request.
/// </summary>
public HttpMethod Method { get; private set; } = HttpMethod.Get;
/// <summary>
/// Gets the request headers.
/// </summary>
public Dictionary<string, string> RequestHeaders { get; private set; } = [];
/// <summary>
/// Gets the content headers.
/// </summary>
public Dictionary<string, string> ContentHeaders { get; private set; } = [];
/// <summary>
/// Gets the query parameters.
/// </summary>
public Dictionary<string, string> QueryParams { get; private set; } = [];
/// <summary>
/// Gets the JSON body content of the request.
/// </summary>
public object Body { get; private set; } = null;
/// <summary>
/// Gets the binary document content of the request.
/// </summary>
public byte[] DocumentBody { get; private set; } = null;
/// <summary>
/// Gets the name of the binary document file.
/// </summary>
public string? DocumentFileName { get; private set; } = null;
/// <summary>
/// Gets the content type of the request.
/// </summary>
public string ContentType { get; private set; } = null;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the Request class with the specified URL.
/// </summary>
/// <param name="url">The URL to send the request to.</param>
public Request(string url)
{
URL = url;
}
/// <summary>
/// Initializes a new instance of the Request class with the specified URL and HTTP method.
/// </summary>
/// <param name="url">The URL to send the request to.</param>
/// <param name="method">The HTTP method to use for the request.</param>
public Request(string url, HttpMethod method): this(url)
{
Method = method;
}
#endregion
#region Functions to update variables
/// <summary>
/// Adds a header to the request.
/// </summary>
/// <param name="key">The header key.</param>
/// <param name="value">The header value.</param>
/// <returns>Instance</returns>
public Request AddHeader(string key, string value)
{
RequestHeaders.Add(key, value);
return this;
}
/// <summary>
/// Adds multiple headers from a dictionary of key-value pairs to the request.
/// </summary>
/// <param name="headers">Headers in dictionary.</param>
/// <returns>Instance</returns>
public Request AddHeaders(Dictionary<string, string> headers)
{
foreach (KeyValuePair<string, string> header in headers)
{
RequestHeaders.Add(header.Key, header.Value);
}
return this;
}
/// <summary>
/// Sets the authorization header.
/// In case of an existing Authorization header, its value
/// will be replaced with the last set.
/// </summary>
/// <param name="value">Authorization header value</param>
/// <returns>Instance</returns>
public Request SetAuthorization(string value)
{
KeyValuePair<string, string>? existingAuthorization = RequestHeaders
.Where(rh => rh.Key == "Authorization")
.FirstOrDefault();
if (existingAuthorization.Equals(new KeyValuePair<string, string>()))
{
AddHeader("Authorization", value);
}
else
{
RequestHeaders[existingAuthorization.Value.Key] = value;
}
return this;
}
/// <summary>
/// Adds a content header to the request
/// </summary>
/// <param name="key">The content header key.</param>
/// <param name="value">The content header value.</param>
/// <returns>Instance</returns>
public Request AddContentHeader(string key, string value)
{
ContentHeaders.Add(key, value);
return this;
}
/// <summary>
/// Adds multiple content headers from a dictionary of key-value pairs to the request.
/// </summary>
/// <param name="headers">Content headers in dictionary.</param>
/// <returns>Instance</returns>
public Request AddContentHeaders(Dictionary<string, string> headers)
{
foreach (KeyValuePair<string, string> header in headers)
{
ContentHeaders.Add(header.Key, header.Value);
}
return this;
}
/// <summary>
/// Adds a query parameter to the request.
/// </summary>
/// <param name="key">The query parameter key.</param>
/// <param name="value">The query parameter value.</param>
/// <returns>Instance</returns>
public Request AddQueryParam(string key, string value)
{
QueryParams.Add(key, value);
return this;
}
/// <summary>
/// Adds multiple content headers from a dictionary of key-value pairs to the request.
/// </summary>
/// <param name="queryParams">Query parameters in dictionary.</param>
/// <returns>Instance</returns>
public Request AddQueryParams(Dictionary<string, string> queryParams)
{
foreach (KeyValuePair<string, string> query in queryParams)
{
QueryParams.Add(query.Key, query.Value);
}
return this;
}
/// <summary>
/// Adds an "Accept" header with the value "application/json" to the request.
/// </summary>
/// <returns>Instance</returns>
public Request AcceptJson()
{
RequestHeaders.Add("Accept", "application/json");
return this;
}
/// <summary>
/// Adds a JSON body to the request content.
/// </summary>
/// <param name="body">The JSON body content.</param>
/// <returns>Instance</returns>
public Request AddJsonBody(object body)
{
Body = body;
_isJsonBody = true;
return this;
}
/// <summary>
/// Adds a <see cref="byte[]"/> to the request content.
/// </summary>
/// <param name="document">The binary file content.</param>
/// <param name="fileName">The name of the file.</param>
/// <returns>Instance</returns>
public Request AddByteBody(byte[] document, string? fileName)
{
DocumentBody = document;
DocumentFileName = fileName;
return this;
}
public Request AddTextBody(object body)
{
Body = body;
_isJsonBody = false;
return this;
}
/// <summary>
/// Sets the content type of the request.
/// </summary>
/// <param name="contentType">The content type of the request.</param>
/// <returns>Instance</returns>
public Request SetContentType(string contentType)
{
ContentType = contentType;
return this;
}
#endregion
#region Peform request
/// <summary>
/// Executes the HTTP request with the JSON body content included.
/// </summary>
/// <typeparam name="T">The type of the response expected from the request.</typeparam>
/// <returns>A Result object containing the response.</returns>
public async Task<Result<T>> Run<T>()
{
HttpRequestMessage request = BuildBaseRequest();
if (Body != null)
{
if (_isJsonBody)
{
string json = JsonConvert.SerializeObject(Body, _jsonSerializerSettings);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
request.Content.Headers.ContentType = new("application/json");
} else
{
request.Content = new StringContent((string)Body, Encoding.UTF8, "text/plain");
request.Content.Headers.ContentType = new("text/plain");
}
}
Result<T> result = await Process<T>(request);
return result;
}
/// <summary>
/// Executes the HTTP request and returns the response content as a byte array.
/// </summary>
/// <typeparam name="T">The type of the response expected from the request.</typeparam>
/// <returns>A Result object containing the response.</returns>
public async Task<Result<T>> RunDocument<T>()
{
HttpRequestMessage request = BuildBaseRequest();
if (DocumentBody == null)
{
return new Result<T>()
{
Error = "Document cannot be null",
StatusCode = 500,
};
}
MultipartFormDataContent content = new();
ByteArrayContent fileContent = new(DocumentBody);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("binary")
{
Name = "file",
FileName = DocumentFileName
};
content.Add(fileContent);
request.Content = content;
request.Content.Headers.ContentType = new(ContentType);
Result<T> result = await Process<T>(request);
return result;
}
/// <summary>
/// Executes the HTTP request that will return a byte array.
/// </summary>
/// <returns>
/// A <see cref="Result{T}"/> object containing the response content as a byte array,
/// the status code of the response, and any error message if the request fails.
/// </returns>
public async Task<Result<byte[]>> RunGetBytes()
{
HttpRequestMessage request = BuildBaseRequest();
Result<byte[]> result = new();
try
{
HttpResponseMessage response = await _httpClient.SendAsync(request);
result.StatusCode = (int)response.StatusCode;
if (response.IsSuccessStatusCode)
{
result.Value = await response.Content.ReadAsByteArrayAsync();
}
else
{
result.Error = await response.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
result.StatusCode = 500;
result.Error = ex.Message;
}
return result;
}
/// <summary>
/// Executes the HTTP request by sending the raw binary content directly in the request body,
/// without using multipart encoding. This method is ideal for APIs expecting direct binary content,
/// equivalent to Postman's "Binary" body type.
/// </summary>
/// <typeparam name="T">The type of the expected response.</typeparam>
/// <returns>
/// A <see cref="Result{T}"/> object containing the deserialized response, the HTTP status code,
/// and any error message if the request fails.
/// </returns>
public async Task<Result<T>> RunBinaryRaw<T>()
{
HttpRequestMessage request = BuildBaseRequest();
if (DocumentBody == null)
{
return new Result<T>
{
Error = "Document cannot be null",
StatusCode = 500
};
}
request.Content = new ByteArrayContent(DocumentBody);
request.Content.Headers.ContentType = new MediaTypeHeaderValue(ContentType ?? "application/octet-stream");
return await Process<T>(request);
}
#endregion
#region Private methods
/// <summary>
/// Constructs the URL for the request, including any query parameters if present.
/// </summary>
/// <returns>Request URL with added query parameters.</returns>
private string BuildUrl()
{
StringBuilder builder = new(URL);
string fullUrl = URL;
if (fullUrl.EndsWith("/"))
builder.Remove(fullUrl.Length - 1, 1);
if (QueryParams.Count() > 0)
{
builder.Append("?");
for (int i = 0; i < QueryParams.Count(); i++)
{
KeyValuePair<string, string> query = QueryParams.ElementAt(i);
builder.Append($"{query.Key}={query.Value}");
if (!(i == QueryParams.Count() - 1))
builder.Append("&");
}
}
return builder.ToString();
}
/// <summary>
/// Constructs the base HTTP request message by adding the specified headers.
/// </summary>
/// <returns>Base request message.</returns>
private HttpRequestMessage BuildBaseRequest()
{
HttpRequestMessage request = new(Method, BuildUrl());
for (int i = 0; i < RequestHeaders.Count(); i++)
{
KeyValuePair<string, string> header = RequestHeaders.ElementAt(i);
request.Headers.Add(header.Key, header.Value);
}
return request;
}
/// <summary>
/// Executes the HTTP request and processes the response.
/// </summary>
/// <typeparam name="T">The type of the response expected from the request.</typeparam>
/// <param name="request">The prepared HTTP request message.</param>
/// <returns>A Result object containing the response.</returns>
private async Task<Result<T>> Process<T>(HttpRequestMessage request)
{
HttpResponseMessage response;
Result<T> result = new();
try
{
response = await _httpClient.SendAsync(request);
result.StatusCode = (int)response.StatusCode;
if (
response.Content == null ||
string.IsNullOrEmpty(await response.Content.ReadAsStringAsync())
)
{
result.Value = default;
return result;
}
if (response.IsSuccessStatusCode)
{
string? mediaType = response.Content?.Headers?.ContentType?.MediaType.ToLower();
string contentResponse = await response.Content?.ReadAsStringAsync();
switch (true)
{
case bool b when (mediaType.Contains("xml")):
XmlSerializer xmlSerializer = new(typeof(T));
StringReader reader = new(contentResponse);
result.Value = (T)xmlSerializer.Deserialize(reader);
break;
case bool b when (mediaType.Contains("application/json")):
result.Value = JsonConvert.DeserializeObject<T>(contentResponse);
break;
default:
result.Value = default;
break;
}
}
else
{
result.Error = await response.Content.ReadAsStringAsync();
}
}
catch (TaskCanceledException ex) when (!ex.CancellationToken.IsCancellationRequested)
{
// HttpClient.Timeout dépassé — HttpClient lève TaskCanceledException dans ce cas
result.StatusCode = 408; // Request Timeout
result.Error = $"La requête a expiré ({_httpClient.Timeout.TotalSeconds}s).";
}
catch (TaskCanceledException ex)
{
result.StatusCode = 499;
result.Error = $"La requête a été annulée : {ex.Message}";
}
catch (Exception ex)
{
result.StatusCode = 500;
result.Error = ex.Message;
}
return result;
}
#endregion
}
}