-
Notifications
You must be signed in to change notification settings - Fork 0
/
RestApi.cs
387 lines (318 loc) · 12.5 KB
/
RestApi.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Newtonsoft.Json;
/// <summary>
/// REST API helper.
/// </summary>
public class RestApi {
#region Properties
/// <summary>
/// Base URL to add to each request.
/// </summary>
public string BaseUrl { get; set; }
/// <summary>
/// Username for Basic Auth.
/// </summary>
public string BasicAuthUsername { get; set; }
/// <summary>
/// Password for Basic Auth.
/// </summary>
public string BasicAuthPassword { get; set; }
/// <summary>
/// Headers to add to each request.
/// </summary>
public Dictionary<string, string> GlobalHeaders { get; set; }
/// <summary>
/// SSL Certificate to add to each request.
/// </summary>
public X509Certificate2 ClientCertificate { get; set; }
#endregion
#region Helper objects
/// <summary>
/// Wrapper for a single request.
/// </summary>
public class RestApiWrapper {
/// <summary>
/// When the request started.
/// </summary>
public DateTime Start { get; set; }
/// <summary>
/// When the request ended.
/// </summary>
public DateTime End { get; set; }
/// <summary>
/// How long the request took.
/// </summary>
public TimeSpan Duration { get; set; }
/// <summary>
/// Exception rised during execution, if any.
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// Keeper of the request information.
/// </summary>
public RestApiWrapperRequest Request { get; set; }
/// <summary>
/// Keeper of the response information.
/// </summary>
public RestApiWrapperResponse Response { get; set; }
/// <summary>
/// Keeper of the request information.
/// </summary>
public class RestApiWrapperRequest {
/// <summary>
/// URL to request.
/// </summary>
public string Url { get; set; }
/// <summary>
/// HTTP method to use.
/// </summary>
public string Method { get; set; }
/// <summary>
/// Body to transmit.
/// </summary>
public string Body { get; set; }
/// <summary>
/// Headers trasmitted.
/// </summary>
public Dictionary<string, string> Headers { get; set; }
/// <summary>
/// Basic Auth username.
/// </summary>
public string BasicAuthUsername { get; set; }
/// <summary>
/// Basic Auth password.
/// </summary>
public string BasicAuthPassword { get; set; }
/// <summary>
/// SSL Certificate.
/// </summary>
public X509Certificate2 ClientCertificate { get; set; }
}
/// <summary>
/// Keeper of the response information.
/// </summary>
public class RestApiWrapperResponse {
/// <summary>
/// Response status code.
/// </summary>
public HttpStatusCode StatusCode { get; set; }
/// <summary>
/// Response status description.
/// </summary>
public string StatusDescription { get; set; }
/// <summary>
/// Response headers.
/// </summary>
public Dictionary<string, string> Headers { get; set; }
/// <summary>
/// Response body.
/// </summary>
public string Body { get; set; }
/// <summary>
/// Convert the response body to given type.
/// </summary>
/// <typeparam name="T">Type to convert to.</typeparam>
/// <returns>Converted content.</returns>
public T BodyTo<T>() {
try {
return JsonConvert.DeserializeObject<T>(this.Body);
}
catch {
return default(T);
}
}
}
}
#endregion
#region Main functions
/// <summary>
/// Make a single request.
/// </summary>
/// <param name="url">URL to request.</param>
/// <param name="method">HTTP method to use.</param>
/// <param name="body">Body to transmit.</param>
/// <param name="headers">Headers to transmit.</param>
/// <returns>Wrapper for request attempt.</returns>
public RestApiWrapper Request(string url, string method, object body = null,
Dictionary<string, string> headers = null) {
var wrapper = new RestApiWrapper {
Start = DateTime.Now,
Request = new RestApiWrapper.RestApiWrapperRequest {
Url = this.BaseUrl + url,
Method = method.ToUpper(),
Headers = this.GlobalHeaders,
BasicAuthUsername = this.BasicAuthUsername,
BasicAuthPassword = this.BasicAuthPassword,
ClientCertificate = this.ClientCertificate
}
};
// Add given headers.
if (headers != null) {
if (wrapper.Request.Headers == null) {
wrapper.Request.Headers = new Dictionary<string, string>();
}
foreach (var header in headers) {
wrapper.Request.Headers.Add(header.Key, header.Value);
}
}
// Prepare body.
if (body != null) {
if (body is string) {
wrapper.Request.Body = body.ToString();
}
else {
wrapper.Request.Body = JsonConvert.SerializeObject(body);
}
}
try {
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Stream stream;
var req = WebRequest.Create(wrapper.Request.Url) as HttpWebRequest;
if (req == null) {
throw new Exception("Unable to create a HttpWebRequest.");
}
req.Method = wrapper.Request.Method;
req.UserAgent = "RestApiWrapper";
// Add basic auth.
if (!string.IsNullOrWhiteSpace(wrapper.Request.BasicAuthUsername) &&
!string.IsNullOrWhiteSpace(wrapper.Request.BasicAuthPassword)) {
var b64e = Convert.ToBase64String(
Encoding.UTF8.GetBytes(
string.Format("{0}:{1}",
wrapper.Request.BasicAuthUsername,
wrapper.Request.BasicAuthPassword)));
req.Headers.Add(
"Authorization",
string.Format("Basic {0}",
b64e));
}
// Add client certificate.
if (wrapper.Request.ClientCertificate != null) {
req.ClientCertificates.Add(wrapper.Request.ClientCertificate);
}
// Add body.
if (!string.IsNullOrWhiteSpace(wrapper.Request.Body)) {
var bytes = Encoding.UTF8.GetBytes(wrapper.Request.Body);
req.ContentLength = bytes.Length;
req.ContentType = "application/json; charset=utf-8";
stream = req.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
}
// Store request headers.
if (wrapper.Request.Headers == null) {
wrapper.Request.Headers = new Dictionary<string, string>();
}
foreach (var key in req.Headers.AllKeys) {
if (wrapper.Request.Headers.ContainsKey(key)) {
continue;
}
wrapper.Request.Headers.Add(key, req.Headers[key]);
}
// Get response.
var res = req.GetResponse() as HttpWebResponse;
if (res == null) {
throw new Exception("Unable to get HttpWebResponse.");
}
if (wrapper.Response == null) {
wrapper.Response = new RestApiWrapper.RestApiWrapperResponse();
}
wrapper.Response.StatusCode = res.StatusCode;
wrapper.Response.StatusDescription = res.StatusDescription;
// Get response headers.
if (res.Headers.AllKeys.Any()) {
if (wrapper.Response.Headers == null) {
wrapper.Response.Headers = new Dictionary<string, string>();
}
foreach (var key in res.Headers.AllKeys) {
wrapper.Response.Headers.Add(key, res.Headers[key]);
}
}
// Get response body.
stream = res.GetResponseStream();
if (stream != null) {
var reader = new StreamReader(stream, Encoding.UTF8);
wrapper.Response.Body = reader.ReadToEnd();
}
}
catch (WebException ex) {
wrapper.Exception = ex;
var res = ex.Response as HttpWebResponse;
if (res != null) {
if (wrapper.Response == null) {
wrapper.Response = new RestApiWrapper.RestApiWrapperResponse();
}
wrapper.Response.StatusCode = res.StatusCode;
wrapper.Response.StatusDescription = res.StatusDescription;
var stream = res.GetResponseStream();
if (stream != null) {
var reader = new StreamReader(stream, Encoding.UTF8);
wrapper.Response.Body = reader.ReadToEnd();
}
}
}
catch (Exception ex) {
wrapper.Exception = ex;
}
wrapper.End = DateTime.Now;
wrapper.Duration = wrapper.End - wrapper.Start;
return wrapper;
}
#endregion
#region Short-hand functions
/// <summary>
/// Short-hand function for a 'GET' request.
/// </summary>
/// <param name="url">URL to request.</param>
/// <param name="headers">Headers to transmit.</param>
/// <returns>Wrapper for request attempt.</returns>
public RestApiWrapper Get(string url = null, Dictionary<string, string> headers = null) {
return Request(url, "GET", null, headers);
}
/// <summary>
/// Short-hand function for a 'POST' request.
/// </summary>
/// <param name="url">URL to request.</param>
/// <param name="body">Body to transmit.</param>
/// <param name="headers">Headers to transmit.</param>
/// <returns>Wrapper for request attempt.</returns>
public RestApiWrapper Post(string url = null, object body = null, Dictionary<string, string> headers = null) {
return Request(url, "POST", body, headers);
}
/// <summary>
/// Short-hand function for a 'PUT' request.
/// </summary>
/// <param name="url">URL to request.</param>
/// <param name="body">Body to transmit.</param>
/// <param name="headers">Headers to transmit.</param>
/// <returns>Wrapper for request attempt.</returns>
public RestApiWrapper Put(string url = null, object body = null, Dictionary<string, string> headers = null) {
return Request(url, "PUT", body, headers);
}
/// <summary>
/// Short-hand function for a 'DELETE' request.
/// </summary>
/// <param name="url">URL to request.</param>
/// <param name="body">Body to transmit.</param>
/// <param name="headers">Headers to transmit.</param>
/// <returns>Wrapper for request attempt.</returns>
public RestApiWrapper Delete(string url = null, object body = null, Dictionary<string, string> headers = null) {
return Request(url, "DELETE", body, headers);
}
/// <summary>
/// Short-hand function for a 'HEAD' request.
/// </summary>
/// <param name="url">URL to request.</param>
/// <param name="headers">Headers to transmit.</param>
/// <returns>Wrapper for request attempt.</returns>
public RestApiWrapper Head(string url = null, Dictionary<string, string> headers = null) {
return Request(url, "HEAD", null, headers);
}
#endregion
}