forked from Pathoschild/FluentHttpClient
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFluentClientExtensions.cs
More file actions
375 lines (336 loc) · 20 KB
/
FluentClientExtensions.cs
File metadata and controls
375 lines (336 loc) · 20 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Pathoschild.Http.Client.Extensibility;
using Pathoschild.Http.Client.Internal;
using Pathoschild.Http.Client.Retry;
namespace Pathoschild.Http.Client
{
/// <summary>Provides convenience methods for configuring the HTTP client.</summary>
public static class FluentClientExtensions
{
/*********
** Public methods
*********/
/****
** IClient
****/
/// <summary>Remove all HTTP filters of the specified type.</summary>
/// <typeparam name="TFilter">The filter type.</typeparam>
/// <param name="filters">The filters to adjust.</param>
/// <returns>Returns whether a filter was removed.</returns>
public static bool Remove<TFilter>(this ICollection<IHttpFilter> filters)
where TFilter : IHttpFilter
{
TFilter[] remove = filters.OfType<TFilter>().ToArray();
foreach (TFilter filter in remove)
filters.Remove(filter);
return remove.Any();
}
/// <summary>Create an asynchronous HTTP DELETE request message (but don't dispatch it yet).</summary>
/// <param name="client">The client.</param>
/// <param name="resource">The URI to send the request to.</param>
/// <returns>Returns a request builder.</returns>
/// <exception cref="ObjectDisposedException">The instance has been disposed.</exception>
public static IRequest DeleteAsync(this IClient client, string resource)
{
return client.SendAsync(HttpMethod.Delete, resource);
}
/// <summary>Create an asynchronous HTTP GET request message (but don't dispatch it yet).</summary>
/// <param name="client">The client.</param>
/// <param name="resource">The URI to send the request to.</param>
/// <returns>Returns a request builder.</returns>
/// <exception cref="ObjectDisposedException">The instance has been disposed.</exception>
public static IRequest GetAsync(this IClient client, string resource)
{
return client.SendAsync(HttpMethod.Get, resource);
}
/// <summary>Create an asynchronous HTTP POST request message (but don't dispatch it yet).</summary>
/// <param name="client">The client.</param>
/// <param name="resource">The URI to send the request to.</param>
/// <returns>Returns a request builder.</returns>
/// <exception cref="ObjectDisposedException">The instance has been disposed.</exception>
public static IRequest PostAsync(this IClient client, string resource)
{
return client.SendAsync(HttpMethod.Post, resource);
}
/// <summary>Create an asynchronous HTTP POST request message (but don't dispatch it yet).</summary>
/// <param name="client">The client.</param>
/// <typeparam name="TBody">The request body type.</typeparam>
/// <param name="resource">The URI to send the request to.</param>
/// <param name="body">The request body.</param>
/// <returns>Returns a request builder.</returns>
/// <exception cref="ObjectDisposedException">The instance has been disposed.</exception>
public static IRequest PostAsync<TBody>(this IClient client, string resource, TBody body)
{
return client.PostAsync(resource).WithBody(body);
}
/// <summary>Create an asynchronous HTTP PUT request message (but don't dispatch it yet).</summary>
/// <param name="client">The client.</param>
/// <param name="resource">The URI to send the request to.</param>
/// <returns>Returns a request builder.</returns>
/// <exception cref="ObjectDisposedException">The instance has been disposed.</exception>
public static IRequest PutAsync(this IClient client, string resource)
{
return client.SendAsync(HttpMethod.Put, resource);
}
/// <summary>Create an asynchronous HTTP PUT request message (but don't dispatch it yet).</summary>
/// <param name="client">The client.</param>
/// <typeparam name="TBody">The request body type.</typeparam>
/// <param name="resource">The URI to send the request to.</param>
/// <param name="body">The request body.</param>
/// <returns>Returns a request builder.</returns>
/// <exception cref="ObjectDisposedException">The instance has been disposed.</exception>
public static IRequest PutAsync<TBody>(this IClient client, string resource, TBody body)
{
return client.PutAsync(resource).WithBody(body);
}
/// <summary>Create an asynchronous HTTP PATCH request message (but don't dispatch it yet).</summary>
/// <param name="client">The client.</param>
/// <param name="resource">The URI to send the request to.</param>
/// <returns>Returns a request builder.</returns>
/// <exception cref="ObjectDisposedException">The instance has been disposed.</exception>
public static IRequest PatchAsync(this IClient client, string resource)
{
return client.SendAsync(new HttpMethod("PATCH"), resource);
}
/// <summary>Create an asynchronous HTTP PATCH request message (but don't dispatch it yet).</summary>
/// <param name="client">The client.</param>
/// <typeparam name="TBody">The request body type.</typeparam>
/// <param name="resource">The URI to send the request to.</param>
/// <param name="body">The request body.</param>
/// <returns>Returns a request builder.</returns>
/// <exception cref="ObjectDisposedException">The instance has been disposed.</exception>
public static IRequest PatchAsync<TBody>(this IClient client, string resource, TBody body)
{
return client.PatchAsync(resource).WithBody(body);
}
/// <summary>Create an asynchronous HTTP request message (but don't dispatch it yet).</summary>
/// <param name="client">The client.</param>
/// <param name="method">The HTTP method.</param>
/// <param name="resource">The URI to send the request to.</param>
/// <returns>Returns a request builder.</returns>
/// <exception cref="ObjectDisposedException">The instance has been disposed.</exception>
public static IRequest SendAsync(this IClient client, HttpMethod method, string resource)
{
var uri = FluentClientExtensions.ResolveFinalUrl(client.BaseClient.BaseAddress, resource);
var message = Factory.GetRequestMessage(method, uri, client.Formatters);
return client.SendAsync(message);
}
/// <summary>Set the default authentication header using basic auth.</summary>
/// <param name="client">The client.</param>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
public static IClient SetBasicAuthentication(this IClient client, string username, string password)
{
return client.SetAuthentication("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Concat(username, ":", password))));
}
/// <summary>Set the default authentication header using a bearer token.</summary>
/// <param name="client">The client.</param>
/// <param name="token">The bearer token (typically an API key).</param>
public static IClient SetBearerAuthentication(this IClient client, string token)
{
return client.SetAuthentication("Bearer", token);
}
/// <summary>Set the default request coordinator.</summary>
/// <param name="client">The client.</param>
/// <param name="shouldRetry">A method which returns whether a request should be retried.</param>
/// <param name="intervals">The intervals between each retry attempt.</param>
public static IClient SetRequestCoordinator(this IClient client, Func<HttpResponseMessage, bool> shouldRetry, params TimeSpan[] intervals)
{
return client.SetRequestCoordinator(new RetryCoordinator(shouldRetry, intervals));
}
/// <summary>Set the default request coordinator.</summary>
/// <param name="client">The client.</param>
/// <param name="maxRetries">The maximum number of times to retry a request before failing.</param>
/// <param name="shouldRetry">A method which returns whether a request should be retried.</param>
/// <param name="getDelay">A method which returns the time to wait until the next retry. This is passed the retry index (starting at 1) and the last HTTP response received.</param>
public static IClient SetRequestCoordinator(this IClient client, int maxRetries, Func<HttpResponseMessage, bool> shouldRetry, Func<int, HttpResponseMessage, TimeSpan> getDelay)
{
return client.SetRequestCoordinator(new RetryCoordinator(maxRetries, shouldRetry, getDelay));
}
/// <summary>Set the default request coordinator.</summary>
/// <param name="client">The client.</param>
/// <param name="config">The retry configuration (or null for the default coordinator).</param>
public static IClient SetRequestCoordinator(this IClient client, IRetryConfig config)
{
return client.SetRequestCoordinator(new RetryCoordinator(config));
}
/// <summary>Set default options for all requests.</summary>
/// <param name="client">The client.</param>
/// <param name="ignoreHttpErrors">Whether to ignore null arguments when the request is dispatched (or <c>null</c> to leave the option unchanged).</param>
/// <param name="ignoreNullArguments">Whether HTTP error responses like HTTP 404 should be ignored; else raised as exceptions (or <c>null</c> to leave the option unchanged).</param>
public static IClient SetOptions(this IClient client, bool? ignoreHttpErrors = null, bool? ignoreNullArguments = null)
{
return client.SetOptions(new FluentClientOptions
{
IgnoreHttpErrors = ignoreHttpErrors,
IgnoreNullArguments = ignoreNullArguments
});
}
/****
** IRequest
****/
/// <summary>Add an authentication header using basic auth.</summary>
/// <param name="request">The request.</param>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
public static IRequest WithBasicAuthentication(this IRequest request, string username, string password)
{
return request.WithAuthentication("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Concat(username, ":", password))));
}
/// <summary>Add an authentication header using a bearer token.</summary>
/// <param name="request">The request.</param>
/// <param name="token">The bearer token (typically an API key).</param>
public static IRequest WithBearerAuthentication(this IRequest request, string token)
{
return request.WithAuthentication("Bearer", token);
}
/// <summary>Set the body content of the HTTP request.</summary>
/// <param name="request">The request.</param>
/// <param name="body">The model to serialize into the HTTP body content, or an <c>HttpContent</c> instance.</param>
/// <returns>Returns the request builder for chaining.</returns>
/// <exception cref="InvalidOperationException">No MediaTypeFormatters are available on the API client for this content type.</exception>
public static IRequest WithBody<T>(this IRequest request, T body)
{
// HttpContent
if (typeof(HttpContent).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo()))
return request.WithBody(p => (HttpContent)(object)body);
// model
return request.WithBody(p => p.Model(body));
}
/// <summary>Set the body content of the HTTP request.</summary>
/// <param name="request">The request.</param>
/// <param name="body">The model to serialize into the HTTP body content.</param>
/// <param name="contentType">The request body format (or <c>null</c> to use the first supported Content-Type in the <see cref="Formatters"/>).</param>
/// <returns>Returns the request builder for chaining.</returns>
/// <exception cref="InvalidOperationException">No MediaTypeFormatters are available on the API client for this content type.</exception>
[Obsolete("Will be removed in 4.0. Use `" + nameof(WithBody) + "` with a builder instead.")]
public static IRequest WithBody<T>(this IRequest request, T body, MediaTypeHeaderValue contentType = null)
{
return request.WithBody(p => p.Model(body, contentType));
}
/// <summary>Set the body content of the HTTP request.</summary>
/// <param name="request">The request.</param>
/// <param name="body">The model to serialize into the HTTP body content.</param>
/// <param name="formatter">The media type formatter with which to format the request body format.</param>
/// <param name="mediaType">The HTTP media type (or <c>null</c> for the <paramref name="formatter"/>'s default).</param>
/// <returns>Returns the request builder for chaining.</returns>
[Obsolete("Will be removed in 4.0. Use `" + nameof(WithBody) + "` with a builder instead.")]
public static IRequest WithBody<T>(this IRequest request, T body, MediaTypeFormatter formatter, string mediaType = null)
{
return request.WithBody(p => p.Model(body, formatter, mediaType));
}
/// <summary>Set the request coordinator for this request</summary>
/// <param name="request">The request.</param>
/// <param name="shouldRetry">A lambda which returns whether a request should be retried.</param>
/// <param name="intervals">The intervals between each retry attempt.</param>
public static IRequest WithRequestCoordinator(this IRequest request, Func<HttpResponseMessage, bool> shouldRetry, params TimeSpan[] intervals)
{
return request.WithRequestCoordinator(new RetryCoordinator(shouldRetry, intervals));
}
/// <summary>Set the request coordinator for this request</summary>
/// <param name="request">The request.</param>
/// <param name="maxRetries">The maximum number of times to retry a request before failing.</param>
/// <param name="shouldRetry">A method which returns whether a request should be retried.</param>
/// <param name="getDelay">A method which returns the time to wait until the next retry. This is passed the retry index (starting at 1) and the last HTTP response received.</param>
public static IRequest WithRequestCoordinator(this IRequest request, int maxRetries, Func<HttpResponseMessage, bool> shouldRetry, Func<int, HttpResponseMessage, TimeSpan> getDelay)
{
return request.WithRequestCoordinator(new RetryCoordinator(maxRetries, shouldRetry, getDelay));
}
/// <summary>Set the request coordinator for this request</summary>
/// <param name="request">The request.</param>
/// <param name="config">The retry config (or null to use the default behaviour).</param>
public static IRequest WithRequestCoordinator(this IRequest request, IRetryConfig config)
{
return request.WithRequestCoordinator(new RetryCoordinator(config));
}
/// <summary>Set options for this request.</summary>
/// <param name="request">The request.</param>
/// <param name="ignoreHttpErrors">Whether to ignore null arguments when the request is dispatched (or <c>null</c> to leave the option unchanged).</param>
/// <param name="ignoreNullArguments">Whether HTTP error responses like HTTP 404 should be ignored; else raised as exceptions (or <c>null</c> to leave the option unchanged).</param>
public static IRequest WithOptions(this IRequest request, bool? ignoreHttpErrors = null, bool? ignoreNullArguments = null)
{
return request.WithOptions(new RequestOptions
{
IgnoreHttpErrors = ignoreHttpErrors,
IgnoreNullArguments = ignoreNullArguments
});
}
/*********
** Internal methods
*********/
/// <summary>Get a copy of the request.</summary>
/// <param name="request">The request to copy.</param>
/// <remarks>Note that cloning a request isn't possible after it's dispatched, because the content stream is automatically disposed after the request.</remarks>
internal static async Task<HttpRequestMessage> CloneAsync(this HttpRequestMessage request)
{
HttpRequestMessage clone = new HttpRequestMessage(request.Method, request.RequestUri)
{
Content = await request.Content.CloneAsync().ConfigureAwait(false),
Version = request.Version
};
foreach (var prop in request.Properties)
clone.Properties.Add(prop);
foreach (var header in request.Headers)
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
return clone;
}
/// <summary>Get a copy of the request content.</summary>
/// <param name="content">The content to copy.</param>
/// <remarks>Note that cloning content isn't possible after it's dispatched, because the stream is automatically disposed after the request.</remarks>
internal static async Task<HttpContent> CloneAsync(this HttpContent content)
{
if (content == null)
return null;
Stream stream = new MemoryStream();
await content.CopyToAsync(stream).ConfigureAwait(false);
stream.Position = 0;
StreamContent clone = new StreamContent(stream);
foreach (var header in content.Headers)
clone.Headers.Add(header.Key, header.Value);
return clone;
}
/// <summary>Resolve the final URL for a request.</summary>
/// <param name="baseUrl">The base URL.</param>
/// <param name="resource">The requested resource.</param>
private static Uri ResolveFinalUrl(Uri baseUrl, string resource)
{
// ignore if empty or already absolute
if (string.IsNullOrWhiteSpace(resource))
return baseUrl;
if (Uri.TryCreate(resource, UriKind.Absolute, out Uri absoluteUrl))
return absoluteUrl;
// parse URLs
resource = resource.Trim();
UriBuilder builder = new UriBuilder(baseUrl);
// special case: combine if either side is a fragment
if (!string.IsNullOrWhiteSpace(builder.Fragment) || resource.StartsWith("#"))
return new Uri(baseUrl + resource);
// special case: if resource is a query string, validate and append it
if (resource.StartsWith("?") || resource.StartsWith("&"))
{
bool baseHasQuery = !string.IsNullOrWhiteSpace(builder.Query);
if (baseHasQuery && resource.StartsWith("?"))
throw new FormatException($"Can't add resource name '{resource}' to base URL '{baseUrl}' because the latter already has a query string.");
if (!baseHasQuery && resource.StartsWith("&"))
throw new FormatException($"Can't add resource name '{resource}' to base URL '{baseUrl}' because the latter doesn't have a query string.");
return new Uri(baseUrl + resource);
}
// else make absolute URL
if (!builder.Path.EndsWith("/"))
{
builder.Path += "/";
baseUrl = builder.Uri;
}
return new Uri(baseUrl, resource);
}
}
}