forked from Pathoschild/FluentHttpClient
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFluentClient.cs
More file actions
237 lines (197 loc) · 9.2 KB
/
FluentClient.cs
File metadata and controls
237 lines (197 loc) · 9.2 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
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
using Pathoschild.Http.Client.Extensibility;
using Pathoschild.Http.Client.Internal;
using Pathoschild.Http.Client.Retry;
namespace Pathoschild.Http.Client
{
/// <inheritdoc cref="IClient" />
[SuppressMessage("ReSharper", "UnusedMember.Global", Justification = "This is a public API.")]
public class FluentClient : IClient
{
/*********
** Fields
*********/
/// <summary>Whether the instance has been disposed.</summary>
private bool IsDisposed;
/// <summary>Whether to dispose the <see cref="BaseClient"/> when disposing.</summary>
private readonly bool MustDisposeBaseClient;
/// <summary>The default behaviors to apply to all requests.</summary>
private readonly IList<Func<IRequest, IRequest>> Defaults = new List<Func<IRequest, IRequest>>();
/// <summary>Options for the fluent client.</summary>
private readonly FluentClientOptions Options = new();
/*********
** Accessors
*********/
/// <inheritdoc />
public ICollection<IHttpFilter> Filters { get; } = new List<IHttpFilter> { new DefaultErrorFilter() };
/// <inheritdoc />
public HttpClient BaseClient { get; }
/// <inheritdoc />
public MediaTypeFormatterCollection Formatters { get; } = new();
/// <inheritdoc />
public IRequestCoordinator? RequestCoordinator { get; private set; }
/*********
** Public methods
*********/
/// <summary>Construct an instance with no base URL.</summary>
public FluentClient()
: this(null, GetDefaultClient(), manageBaseClient: true) { }
/// <summary>Construct an instance.</summary>
/// <param name="baseUri">The base URI prepended to relative request URIs.</param>
public FluentClient(string? baseUri)
: this(baseUri != null ? new Uri(baseUri) : null, GetDefaultClient(), manageBaseClient: true) { }
/// <summary>Construct an instance.</summary>
/// <param name="baseUri">The base URI prepended to relative request URIs.</param>
public FluentClient(Uri? baseUri)
: this(baseUri, GetDefaultClient(), manageBaseClient: true) { }
/// <summary>Construct an instance.</summary>
/// <param name="baseUri">The base URI prepended to relative request URIs.</param>
/// <param name="proxy">The web proxy.</param>
public FluentClient(Uri? baseUri, IWebProxy? proxy)
: this(baseUri, new HttpClient(GetDefaultHandler(proxy)), manageBaseClient: true) { }
/// <summary>Construct an instance.</summary>
/// <param name="baseUri">The base URI prepended to relative request URIs.</param>
/// <param name="baseClient">The underlying HTTP client.</param>
/// <param name="manageBaseClient">Whether to dispose the <paramref name="baseClient"/> when the instance is disposed.</param>
public FluentClient(Uri? baseUri, HttpClient? baseClient, bool manageBaseClient = false)
{
this.MustDisposeBaseClient = baseClient == null || manageBaseClient;
this.BaseClient = baseClient ?? new HttpClient(GetDefaultHandler());
if (baseUri != null)
this.BaseClient.BaseAddress = baseUri;
this.SetDefaultUserAgent();
}
/// <summary>Construct an instance.</summary>
/// <param name="baseClient">The underlying HTTP client.</param>
/// <param name="manageBaseClient">Whether to dispose the <paramref name="baseClient"/> when the instance is disposed.</param>
public FluentClient(HttpClient? baseClient, bool manageBaseClient = false)
: this(null, baseClient, manageBaseClient) { }
/// <inheritdoc />
public virtual IRequest SendAsync(HttpRequestMessage message)
{
this.AssertNotDisposed();
IRequest request = new Request(message, this.Formatters, async req => await this.SendImplAsync(req).ConfigureAwait(false), this.Filters.ToList()) // clone the underlying message because HttpClient doesn't normally allow re-sending the same request, which would break IRequestCoordinator
.WithRequestCoordinator(this.RequestCoordinator)
.WithOptions(this.Options.ToRequestOptions());
foreach (Func<IRequest, IRequest> apply in this.Defaults)
request = apply(request);
return request;
}
/// <inheritdoc />
public IClient SetAuthentication(string scheme, string parameter)
{
this.BaseClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(scheme, parameter);
return this;
}
/// <inheritdoc />
public IClient SetOptions(FluentClientOptions options)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
this.Options.MergeFrom(options);
return this;
}
/// <inheritdoc />
public IClient SetUserAgent(string userAgent)
{
this.BaseClient.DefaultRequestHeaders.Remove("User-Agent");
this.BaseClient.DefaultRequestHeaders.Add("User-Agent", userAgent);
return this;
}
/// <inheritdoc />
public IClient SetRequestCoordinator(IRequestCoordinator? requestCoordinator)
{
this.RequestCoordinator = requestCoordinator;
return this;
}
/// <inheritdoc />
public IClient AddDefault(Func<IRequest, IRequest> apply)
{
this.Defaults.Add(apply);
return this;
}
/// <inheritdoc />
public virtual void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/*********
** Protected methods
*********/
/// <summary>Set the default user agent header.</summary>
private void SetDefaultUserAgent()
{
Version version = typeof(FluentClient).GetTypeInfo().Assembly.GetName().Version!;
this.SetUserAgent($"FluentHttpClient/{version} (+http://github.com/Pathoschild/FluentHttpClient)");
}
/// <summary>Dispatch an HTTP request message and fetch the response message.</summary>
/// <param name="request">The request to send.</param>
/// <exception cref="ObjectDisposedException">The instance has been disposed.</exception>
protected virtual async Task<HttpResponseMessage> SendImplAsync(IRequest request)
{
this.AssertNotDisposed();
// clone request (to avoid issues when resending messages)
HttpRequestMessage requestMessage = await request.Message.CloneAsync(request.CancellationToken).ConfigureAwait(false);
// dispatch request
return await this.BaseClient
.SendAsync(requestMessage, request.CancellationToken)
.ConfigureAwait(false);
}
/// <summary>Assert that the instance has not been disposed.</summary>
/// <exception cref="ObjectDisposedException">The instance has been disposed.</exception>
protected void AssertNotDisposed()
{
if (this.IsDisposed)
throw new ObjectDisposedException(nameof(FluentClient));
}
/// <summary>Free resources used by the client.</summary>
/// <param name="isDisposing">Whether the dispose method was explicitly called.</param>
protected virtual void Dispose(bool isDisposing)
{
if (this.IsDisposed)
return;
if (isDisposing && this.MustDisposeBaseClient)
this.BaseClient.Dispose();
this.IsDisposed = true;
}
/// <summary>Get a default HTTP client.</summary>
private static HttpClient GetDefaultClient()
{
return new HttpClient(GetDefaultHandler());
}
/// <summary>Get a default HTTP client handler.</summary>
private static HttpClientHandler GetDefaultHandler()
{
return new HttpClientHandler
{
// don't use cookie container (so we can set cookies directly in request headers)
UseCookies = false
};
}
/// <summary>Get a default HTTP client handler.</summary>
/// <param name="proxy">The web proxy to use.</param>
/// <remarks>Whereas <see cref="GetDefaultHandler()"/> leaves the default proxy unchanged, this method will explicitly override it (e.g. setting a null proxy will disable the default proxy).</remarks>
private static HttpClientHandler GetDefaultHandler(IWebProxy? proxy)
{
HttpClientHandler handler = FluentClient.GetDefaultHandler();
handler.Proxy = proxy;
handler.UseProxy = proxy != null;
return handler;
}
/// <summary>Destruct the instance.</summary>
~FluentClient()
{
this.Dispose(false);
}
}
}