-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathApiClient.cs
More file actions
796 lines (715 loc) · 39 KB
/
ApiClient.cs
File metadata and controls
796 lines (715 loc) · 39 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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
/*
* Regula Document Reader Web API
*
* Fast and reliable identity document verification for on-premises installation or cloud integration. # Clients: * [JavaScript](https://github.com/regulaforensics/DocumentReader-web-js-client) client for the browser and node.js based on axios * [Java](https://github.com/regulaforensics/DocumentReader-web-java-client) client compatible with jvm and android * [Python](https://github.com/regulaforensics/DocumentReader-web-python-client) 3.5+ client * [C#](https://github.com/regulaforensics/DocumentReader-web-csharp-client) client for .NET & .NET Core # Documentation Go to [Regula Developer Documentation](https://docs.regulaforensics.com/develop/doc-reader-sdk/web-service) to read the technologies description, licensing information, release notes, and instructions on the integration, installation, migration, etc. # Technical Support To submit a request to the Support Team, visit [Regula Help Center](https://support.regulaforensics.com/hc/en-us/requests/new). # Business Enquiries To discuss business opportunities, fill the [Enquiry Form](https://explore.regula.app/docs-support-request) and specify your scenarios, applications, and technical requirements.
*
* The version of the OpenAPI document: 8.1.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using System.Net.Http;
using System.Net.Http.Headers;
using Polly;
namespace Regula.DocumentReader.WebClient.Client
{
/// <summary>
/// To Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary>
internal class CustomJsonCodec
{
private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json";
private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
public CustomJsonCodec(IReadableConfiguration configuration)
{
_configuration = configuration;
}
public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration)
{
_serializerSettings = serializerSettings;
_configuration = configuration;
}
/// <summary>
/// Serialize the object into a JSON string.
/// </summary>
/// <param name="obj">Object to be serialized.</param>
/// <returns>A JSON string.</returns>
public string Serialize(object obj)
{
if (obj != null && obj is Regula.DocumentReader.WebClient.Model.AbstractOpenAPISchema)
{
// the object to be serialized is an oneOf/anyOf schema
return ((Regula.DocumentReader.WebClient.Model.AbstractOpenAPISchema)obj).ToJson();
}
else
{
return JsonConvert.SerializeObject(obj, _serializerSettings);
}
}
public async Task<T> Deserialize<T>(HttpResponseMessage response)
{
var result = (T) await Deserialize(response, typeof(T)).ConfigureAwait(false);
return result;
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
internal async Task<object> Deserialize(HttpResponseMessage response, Type type)
{
IList<string> headers = new List<string>();
// process response headers, e.g. Access-Control-Allow-Methods
foreach (var responseHeader in response.Headers)
{
headers.Add(responseHeader.Key + "=" + ClientUtils.ParameterToString(responseHeader.Value));
}
// process response content headers, e.g. Content-Type
foreach (var responseHeader in response.Content.Headers)
{
headers.Add(responseHeader.Key + "=" + ClientUtils.ParameterToString(responseHeader.Value));
}
// RFC 2183 & RFC 2616
var fileNameRegex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$", RegexOptions.IgnoreCase);
if (type == typeof(byte[])) // return byte array
{
return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
}
else if (type == typeof(FileParameter))
{
if (headers != null) {
foreach (var header in headers)
{
var match = fileNameRegex.Match(header.ToString());
if (match.Success)
{
string fileName = ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
return new FileParameter(fileName, await response.Content.ReadAsStreamAsync().ConfigureAwait(false));
}
}
}
return new FileParameter(await response.Content.ReadAsStreamAsync().ConfigureAwait(false));
}
// TODO: ? if (type.IsAssignableFrom(typeof(Stream)))
if (type == typeof(Stream))
{
var bytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
if (headers != null)
{
var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath)
? Path.GetTempPath()
: _configuration.TempFolderPath;
foreach (var header in headers)
{
var match = fileNameRegex.Match(header.ToString());
if (match.Success)
{
string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
File.WriteAllBytes(fileName, bytes);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(bytes);
return stream;
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false), null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return Convert.ChangeType(await response.Content.ReadAsStringAsync().ConfigureAwait(false), type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync().ConfigureAwait(false), type, _serializerSettings);
}
catch (Exception e)
{
Console.WriteLine($"Warning: Failed to deserialize response to type {type.Name}: {e.Message}");
return type.IsValueType ? Activator.CreateInstance(type) : null;
}
}
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public string ContentType
{
get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); }
}
}
/// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementations),
/// encapsulating general REST accessor use cases.
/// </summary>
/// <remarks>
/// The Dispose method will manage the HttpClient lifecycle when not passed by constructor.
/// </remarks>
public partial class ApiClient : IDisposable, ISynchronousClient, IAsynchronousClient
{
private readonly string _baseUrl;
private readonly HttpClientHandler _httpClientHandler;
private readonly HttpClient _httpClient;
private readonly bool _disposeClient;
/// <summary>
/// Specifies the settings on a <see cref="JsonSerializer" /> object.
/// These settings can be adjusted to accommodate custom serialization rules.
/// </summary>
public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
},
Error = HandleDeserializationError
};
private static void HandleDeserializationError(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
var currentError = args.ErrorContext.Error.GetBaseException();
Console.WriteLine($"Warning: JSON Deserialization Error at path '{args.ErrorContext.Path}'. Member: '{args.ErrorContext.Member}'. Error: {currentError.Message}.");
args.ErrorContext.Handled = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url.
/// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal.
/// It's better to reuse the <see href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#issues-with-the-original-httpclient-class-available-in-net">HttpClient and HttpClientHandler</see>.
/// </summary>
public ApiClient() :
this(Regula.DocumentReader.WebClient.Client.GlobalConfiguration.Instance.BasePath)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />.
/// **IMPORTANT** This will also create an instance of HttpClient, which is less than ideal.
/// It's better to reuse the <see href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#issues-with-the-original-httpclient-class-available-in-net">HttpClient and HttpClientHandler</see>.
/// </summary>
/// <param name="basePath">The target service's base path in URL format.</param>
/// <exception cref="ArgumentException"></exception>
public ApiClient(string basePath)
{
if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty");
_httpClientHandler = new HttpClientHandler();
_httpClient = new HttpClient(_httpClientHandler, true);
_disposeClient = true;
_baseUrl = basePath;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url.
/// </summary>
/// <param name="client">An instance of HttpClient.</param>
/// <param name="handler">An optional instance of HttpClientHandler that is used by HttpClient.</param>
/// <exception cref="ArgumentNullException"></exception>
/// <remarks>
/// Some configuration settings will not be applied without passing an HttpClientHandler.
/// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings.
/// </remarks>
public ApiClient(HttpClient client, HttpClientHandler handler = null) :
this(client, Regula.DocumentReader.WebClient.Client.GlobalConfiguration.Instance.BasePath, handler)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />.
/// </summary>
/// <param name="client">An instance of HttpClient.</param>
/// <param name="basePath">The target service's base path in URL format.</param>
/// <param name="handler">An optional instance of HttpClientHandler that is used by HttpClient.</param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
/// <remarks>
/// Some configuration settings will not be applied without passing an HttpClientHandler.
/// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings.
/// </remarks>
public ApiClient(HttpClient client, string basePath, HttpClientHandler handler = null)
{
if (client == null) throw new ArgumentNullException("client cannot be null");
if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty");
_httpClientHandler = handler;
_httpClient = client;
_baseUrl = basePath;
}
/// <summary>
/// Disposes resources if they were created by us
/// </summary>
public void Dispose()
{
if(_disposeClient) {
_httpClient.Dispose();
}
}
/// Prepares multipart/form-data content
HttpContent PrepareMultipartFormDataContent(RequestOptions options)
{
string boundary = "---------" + Guid.NewGuid().ToString().ToUpperInvariant();
var multipartContent = new MultipartFormDataContent(boundary);
foreach (var formParameter in options.FormParameters)
{
multipartContent.Add(new StringContent(formParameter.Value), formParameter.Key);
}
if (options.FileParameters != null && options.FileParameters.Count > 0)
{
foreach (var fileParam in options.FileParameters)
{
foreach (var file in fileParam.Value)
{
var content = new StreamContent(file.Content);
content.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
multipartContent.Add(content, fileParam.Key, file.Name);
}
}
}
return multipartContent;
}
/// <summary>
/// Provides all logic for constructing a new HttpRequestMessage.
/// At this point, all information for querying the service is known. Here, it is simply
/// mapped into the a HttpRequestMessage.
/// </summary>
/// <param name="method">The http verb.</param>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>[private] A new HttpRequestMessage instance.</returns>
/// <exception cref="ArgumentNullException"></exception>
private HttpRequestMessage NewRequest(
HttpMethod method,
string path,
RequestOptions options,
IReadableConfiguration configuration)
{
if (path == null) throw new ArgumentNullException("path");
if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration");
WebRequestPathBuilder builder = new WebRequestPathBuilder(_baseUrl, path);
builder.AddPathParameters(options.PathParameters);
builder.AddQueryParameters(options.QueryParameters);
HttpRequestMessage request = new HttpRequestMessage(method, builder.GetFullUri());
if (configuration.UserAgent != null)
{
request.Headers.TryAddWithoutValidation("User-Agent", configuration.UserAgent);
}
if (configuration.DefaultHeaders != null)
{
foreach (var headerParam in configuration.DefaultHeaders)
{
request.Headers.Add(headerParam.Key, headerParam.Value);
}
}
if (options.HeaderParameters != null)
{
foreach (var headerParam in options.HeaderParameters)
{
foreach (var value in headerParam.Value)
{
// Todo make content headers actually content headers
request.Headers.TryAddWithoutValidation(headerParam.Key, value);
}
}
}
List<Tuple<HttpContent, string, string>> contentList = new List<Tuple<HttpContent, string, string>>();
string contentType = null;
if (options.HeaderParameters != null && options.HeaderParameters.ContainsKey("Content-Type"))
{
var contentTypes = options.HeaderParameters["Content-Type"];
contentType = contentTypes.FirstOrDefault();
}
if (contentType == "multipart/form-data")
{
request.Content = PrepareMultipartFormDataContent(options);
}
else if (contentType == "application/x-www-form-urlencoded")
{
request.Content = new FormUrlEncodedContent(options.FormParameters);
}
else
{
if (options.Data != null)
{
if (options.Data is FileParameter fp)
{
contentType = contentType ?? "application/octet-stream";
var streamContent = new StreamContent(fp.Content);
streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
request.Content = streamContent;
}
else
{
var serializer = new CustomJsonCodec(SerializerSettings, configuration);
request.Content = new StringContent(serializer.Serialize(options.Data), new UTF8Encoding(),
"application/json");
}
}
}
// TODO provide an alternative that allows cookies per request instead of per API client
if (options.Cookies != null && options.Cookies.Count > 0)
{
request.Properties["CookieContainer"] = options.Cookies;
}
return request;
}
partial void InterceptRequest(HttpRequestMessage req);
partial void InterceptResponse(HttpRequestMessage req, HttpResponseMessage response);
private async Task<ApiResponse<T>> ToApiResponse<T>(HttpResponseMessage response, object responseData, Uri uri)
{
T result = (T) responseData;
string rawContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>(), result, rawContent)
{
ErrorText = response.ReasonPhrase,
Cookies = new List<Cookie>()
};
// process response headers, e.g. Access-Control-Allow-Methods
if (response.Headers != null)
{
foreach (var responseHeader in response.Headers)
{
transformed.Headers.Add(responseHeader.Key, ClientUtils.ParameterToString(responseHeader.Value));
}
}
// process response content headers, e.g. Content-Type
if (response.Content.Headers != null)
{
foreach (var responseHeader in response.Content.Headers)
{
transformed.Headers.Add(responseHeader.Key, ClientUtils.ParameterToString(responseHeader.Value));
}
}
if (_httpClientHandler != null && response != null)
{
try {
foreach (Cookie cookie in _httpClientHandler.CookieContainer.GetCookies(uri))
{
transformed.Cookies.Add(cookie);
}
}
catch (PlatformNotSupportedException) {}
}
return transformed;
}
private ApiResponse<T> Exec<T>(HttpRequestMessage req, IReadableConfiguration configuration)
{
return ExecAsync<T>(req, configuration).GetAwaiter().GetResult();
}
private async Task<ApiResponse<T>> ExecAsync<T>(HttpRequestMessage req,
IReadableConfiguration configuration,
System.Threading.CancellationToken cancellationToken = default)
{
CancellationTokenSource timeoutTokenSource = null;
CancellationTokenSource finalTokenSource = null;
var deserializer = new CustomJsonCodec(SerializerSettings, configuration);
var finalToken = cancellationToken;
try
{
if (configuration.Timeout > TimeSpan.Zero)
{
timeoutTokenSource = new CancellationTokenSource(configuration.Timeout);
finalTokenSource = CancellationTokenSource.CreateLinkedTokenSource(finalToken, timeoutTokenSource.Token);
finalToken = finalTokenSource.Token;
}
if (configuration.Proxy != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
_httpClientHandler.Proxy = configuration.Proxy;
}
if (configuration.ClientCertificates != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
_httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates);
}
var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List<Cookie> : null;
if (cookieContainer != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
foreach (var cookie in cookieContainer)
{
_httpClientHandler.CookieContainer.Add(cookie);
}
}
InterceptRequest(req);
HttpResponseMessage response;
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
var policyResult = await policy
.ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, finalToken))
.ConfigureAwait(false);
response = (policyResult.Outcome == OutcomeType.Successful) ?
policyResult.Result : new HttpResponseMessage()
{
ReasonPhrase = policyResult.FinalException.ToString(),
RequestMessage = req
};
}
else
{
response = await _httpClient.SendAsync(req, finalToken).ConfigureAwait(false);
}
if (!response.IsSuccessStatusCode)
{
return await ToApiResponse<T>(response, default, req.RequestUri).ConfigureAwait(false);
}
object responseData = await deserializer.Deserialize<T>(response).ConfigureAwait(false);
// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof(Regula.DocumentReader.WebClient.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
}
else if (typeof(T).Name == "Stream") // for binary response
{
responseData = (T) (object) await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
InterceptResponse(req, response);
return await ToApiResponse<T>(response, responseData, req.RequestUri).ConfigureAwait(false);
}
catch (OperationCanceledException original)
{
if (timeoutTokenSource != null && timeoutTokenSource.IsCancellationRequested)
{
throw new TaskCanceledException($"[{req.Method}] {req.RequestUri} was timeout.",
new TimeoutException(original.Message, original));
}
throw;
}
finally
{
if (timeoutTokenSource != null)
{
timeoutTokenSource.Dispose();
}
if (finalTokenSource != null)
{
finalTokenSource.Dispose();
}
}
}
#region IAsynchronousClient
/// <summary>
/// Make a HTTP GET request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> GetAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default)
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP POST request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PostAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default)
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP PUT request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PutAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default)
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP DELETE request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> DeleteAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default)
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP HEAD request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> HeadAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default)
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP OPTION request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> OptionsAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default)
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken);
}
/// <summary>
/// Make a HTTP PATCH request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PatchAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default)
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(new HttpMethod("PATCH"), path, options, config), config, cancellationToken);
}
#endregion IAsynchronousClient
#region ISynchronousClient
/// <summary>
/// Make a HTTP GET request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Get<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Get, path, options, config), config);
}
/// <summary>
/// Make a HTTP POST request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Post<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Post, path, options, config), config);
}
/// <summary>
/// Make a HTTP PUT request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Put<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Put, path, options, config), config);
}
/// <summary>
/// Make a HTTP DELETE request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Delete<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Delete, path, options, config), config);
}
/// <summary>
/// Make a HTTP HEAD request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Head<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Head, path, options, config), config);
}
/// <summary>
/// Make a HTTP OPTION request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Options<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Options, path, options, config), config);
}
/// <summary>
/// Make a HTTP PATCH request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Patch<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(new HttpMethod("PATCH"), path, options, config), config);
}
#endregion ISynchronousClient
}
}