forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceClientBase.cs
More file actions
595 lines (506 loc) · 18 KB
/
Copy pathServiceClientBase.cs
File metadata and controls
595 lines (506 loc) · 18 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
using System;
using System.IO;
using System.Net;
using ServiceStack.Logging;
using ServiceStack.Service;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
namespace ServiceStack.ServiceClient.Web
{
/**
* Need to provide async request options
* http://msdn.microsoft.com/en-us/library/86wf6409(VS.71).aspx
*/
public abstract class ServiceClientBase
#if !SILVERLIGHT
: IServiceClient, IRestClient
#else
: IServiceClient
#endif
{
private static readonly ILog log = LogManager.GetLogger(typeof(ServiceClientBase));
/// <summary>
/// The request filter is called before any request.
/// This request filter is executed globally.
/// </summary>
public static Action<HttpWebRequest> HttpWebRequestFilter { get; set; }
public const string DefaultHttpMethod = "POST";
readonly AsyncServiceClient asyncClient;
protected ServiceClientBase()
{
this.HttpMethod = DefaultHttpMethod;
this.CookieContainer = new CookieContainer();
asyncClient = new AsyncServiceClient {
ContentType = ContentType,
StreamSerializer = SerializeToStream,
StreamDeserializer = StreamDeserializer,
CookieContainer = this.CookieContainer,
};
this.StoreCookies = true; //leave
#if SILVERLIGHT
asyncClient.HandleCallbackOnUIThread = this.HandleCallbackOnUIThread = true;
asyncClient.UseBrowserHttpHandling = this.UseBrowserHttpHandling = false;
asyncClient.ShareCookiesWithBrowser = this.ShareCookiesWithBrowser = true;
#endif
}
protected ServiceClientBase(string syncReplyBaseUri, string asyncOneWayBaseUri)
: this()
{
this.SyncReplyBaseUri = syncReplyBaseUri;
this.AsyncOneWayBaseUri = asyncOneWayBaseUri;
}
public void SetBaseUri(string baseUri, string format)
{
this.BaseUri = baseUri;
this.asyncClient.BaseUri = baseUri;
this.SyncReplyBaseUri = baseUri.WithTrailingSlash() + format + "/syncreply/";
this.AsyncOneWayBaseUri = baseUri.WithTrailingSlash() + format + "/asynconeway/";
}
/// <summary>
/// The user name for basic authentication
/// </summary>
public string UserName { get; set; }
/// <summary>
/// The password for basic authentication
/// </summary>
public string Password { get; set; }
/// <summary>
/// Sets the username and the password for basic authentication.
/// </summary>
public void SetCredentials(string userName, string password)
{
this.UserName = userName;
this.Password = password;
}
public string BaseUri { get; set; }
public string SyncReplyBaseUri { get; set; }
public string AsyncOneWayBaseUri { get; set; }
private TimeSpan? timeout;
public TimeSpan? Timeout
{
get { return this.timeout; }
set
{
this.timeout = value;
this.asyncClient.Timeout = value;
}
}
public abstract string ContentType { get; }
public string HttpMethod { get; set; }
#if !SILVERLIGHT
public IWebProxy Proxy { get; set; }
#endif
#if SILVERLIGHT
private bool handleCallbackOnUiThread;
public bool HandleCallbackOnUIThread
{
get { return this.handleCallbackOnUiThread; }
set { asyncClient.HandleCallbackOnUIThread = this.handleCallbackOnUiThread = value; }
}
private bool useBrowserHttpHandling;
public bool UseBrowserHttpHandling
{
get { return this.useBrowserHttpHandling; }
set { asyncClient.UseBrowserHttpHandling = this.useBrowserHttpHandling = value; }
}
private bool shareCookiesWithBrowser;
public bool ShareCookiesWithBrowser
{
get { return this.shareCookiesWithBrowser; }
set { asyncClient.ShareCookiesWithBrowser = this.shareCookiesWithBrowser = value; }
}
#endif
private ICredentials credentials;
/// <summary>
/// Gets or sets authentication information for the request.
/// Warning: It's recommened to use <see cref="UserName"/> and <see cref="Password"/> for basic auth.
/// This property is only used for IIS level authentication.
/// </summary>
public ICredentials Credentials
{
set
{
this.credentials = value;
this.asyncClient.Credentials = value;
}
}
/// <summary>
/// Determines if the basic auth header should be sent with every request.
/// By default, the basic auth header is only sent when "401 Unauthorized" is returned.
/// </summary>
public bool AlwaysSendBasicAuthHeader { get; set; }
/// <summary>
/// Specifies if cookies should be stored
/// </summary>
private bool storeCookies;
public bool StoreCookies
{
get { return storeCookies; }
set { asyncClient.StoreCookies = storeCookies = value; }
}
public CookieContainer CookieContainer { get; set; }
/// <summary>
/// The request filter is called before any request.
/// This request filter only works with the instance where it was set (not global).
/// </summary>
public Action<HttpWebRequest> LocalHttpWebRequestFilter { get; set; }
public abstract void SerializeToStream(IRequestContext requestContext, object request, Stream stream);
public abstract T DeserializeFromStream<T>(Stream stream);
public abstract StreamDeserializerDelegate StreamDeserializer { get; }
#if !SILVERLIGHT
public virtual TResponse Send<TResponse>(object request)
{
var requestUri = this.SyncReplyBaseUri.WithTrailingSlash() + request.GetType().Name;
var client = SendRequest(requestUri, request);
try
{
using (var responseStream = client.GetResponse().GetResponseStream())
{
var response = DeserializeFromStream<TResponse>(responseStream);
return response;
}
}
catch (Exception ex)
{
TResponse response;
if (!HandleResponseException(ex, Web.HttpMethod.Post, requestUri, request, out response))
{
throw;
}
return response;
}
}
private bool HandleResponseException<TResponse>(Exception ex, string httpMethod, string requestUri, object request, out TResponse response)
{
try
{
if (WebRequestUtils.ShouldAuthenticate(ex, this.UserName, this.Password))
{
var client = SendRequest(httpMethod, requestUri, request);
client.AddBasicAuth(this.UserName, this.Password);
try
{
using (var responseStream = client.GetResponse().GetResponseStream())
{
response = DeserializeFromStream<TResponse>(responseStream);
return true;
}
}
catch { /* Ignore deserializing error exceptions */ }
}
}
catch (Exception subEx)
{
// Since we are effectively re-executing the call,
// the new exception should be shown to the caller rather
// than the old one.
// The new exception is either this one or the one thrown
// by the following method.
HandleResponseException<TResponse>(subEx, requestUri);
throw;
}
// If this doesn't throw, the calling method
// should rethrow the original exception upon
// return value of false.
HandleResponseException<TResponse>(ex, requestUri);
response = default(TResponse);
return false;
}
private void HandleResponseException<TResponse>(Exception ex, string requestUri)
{
var webEx = ex as WebException;
if (webEx != null && webEx.Status == WebExceptionStatus.ProtocolError)
{
var errorResponse = ((HttpWebResponse)webEx.Response);
log.Error(webEx);
log.DebugFormat("Status Code : {0}", errorResponse.StatusCode);
log.DebugFormat("Status Description : {0}", errorResponse.StatusDescription);
var serviceEx = new WebServiceException(errorResponse.StatusDescription) {
StatusCode = (int)errorResponse.StatusCode,
StatusDescription = errorResponse.StatusDescription,
};
try
{
using (var stream = errorResponse.GetResponseStream())
{
serviceEx.ResponseDto = DeserializeFromStream<TResponse>(stream);
}
}
catch (Exception innerEx)
{
// Oh, well, we tried
throw new WebServiceException(errorResponse.StatusDescription, innerEx) {
StatusCode = (int)errorResponse.StatusCode,
StatusDescription = errorResponse.StatusDescription,
};
}
//Escape deserialize exception handling and throw here
throw serviceEx;
}
var authEx = ex as AuthenticationException;
if (authEx != null)
{
throw WebRequestUtils.CreateCustomException(requestUri, authEx);
}
}
private WebRequest SendRequest(string requestUri, object request)
{
return SendRequest(HttpMethod ?? DefaultHttpMethod, requestUri, request);
}
private WebRequest SendRequest(string httpMethod, string requestUri, object request)
{
if (httpMethod == null)
throw new ArgumentNullException("httpMethod");
if (httpMethod == Web.HttpMethod.Get && request != null)
{
var queryString = QueryStringSerializer.SerializeToString(request);
if (!string.IsNullOrEmpty(queryString))
{
requestUri += "?" + queryString;
}
}
var client = (HttpWebRequest)WebRequest.Create(requestUri);
try
{
client.Accept = ContentType;
client.Method = httpMethod;
if (Proxy != null) client.Proxy = Proxy;
if (this.Timeout.HasValue) client.Timeout = (int)this.Timeout.Value.TotalMilliseconds;
if (this.credentials != null) client.Credentials = this.credentials;
if (this.AlwaysSendBasicAuthHeader) client.AddBasicAuth(this.UserName, this.Password);
if (StoreCookies)
{
client.CookieContainer = CookieContainer;
}
if (this.LocalHttpWebRequestFilter != null)
LocalHttpWebRequestFilter(client);
if (HttpWebRequestFilter != null)
HttpWebRequestFilter(client);
if (httpMethod != Web.HttpMethod.Get
&& httpMethod != Web.HttpMethod.Delete)
{
client.ContentType = ContentType;
using (var requestStream = client.GetRequestStream())
{
SerializeToStream(null, request, requestStream);
}
}
}
catch (AuthenticationException ex)
{
throw WebRequestUtils.CreateCustomException(requestUri, ex) ?? ex;
}
return client;
}
#else
private void SendRequest(string requestUri, object request, Action<WebRequest> callback)
{
var isHttpGet = HttpMethod != null && HttpMethod.ToUpper() == "GET";
if (isHttpGet)
{
var queryString = QueryStringSerializer.SerializeToString(request);
if (!string.IsNullOrEmpty(queryString))
{
requestUri += "?" + queryString;
}
}
SendRequest(HttpMethod ?? DefaultHttpMethod, requestUri, request, callback);
}
private void SendRequest(string httpMethod, string requestUri, object request, Action<WebRequest> callback)
{
if (httpMethod == null)
throw new ArgumentNullException("httpMethod");
var client = (HttpWebRequest)WebRequest.Create(requestUri);
try
{
client.Accept = ContentType;
client.Method = httpMethod;
if (this.credentials != null) client.Credentials = this.credentials;
if (this.AlwaysSendBasicAuthHeader) client.AddBasicAuth(this.UserName, this.Password);
if (StoreCookies)
{
client.CookieContainer = CookieContainer;
}
if (this.LocalHttpWebRequestFilter != null)
LocalHttpWebRequestFilter(client);
if (HttpWebRequestFilter != null)
HttpWebRequestFilter(client);
if (httpMethod != Web.HttpMethod.Get
&& httpMethod != Web.HttpMethod.Delete)
{
client.ContentType = ContentType;
client.BeginGetRequestStream(delegate(IAsyncResult target)
{
var webReq = (HttpWebRequest)target.AsyncState;
var requestStream = webReq.EndGetRequestStream(target);
SerializeToStream(null, request, requestStream);
callback(client);
}, null);
}
}
catch (AuthenticationException ex)
{
throw WebRequestUtils.CreateCustomException(requestUri, ex) ?? ex;
}
}
#endif
private string GetUrl(string relativeOrAbsoluteUrl)
{
return relativeOrAbsoluteUrl.StartsWith("http:")
|| relativeOrAbsoluteUrl.StartsWith("https:")
? relativeOrAbsoluteUrl
: this.BaseUri + relativeOrAbsoluteUrl;
}
#if !SILVERLIGHT
private byte[] DownloadBytes(string requestUri, object request)
{
var webRequest = SendRequest(requestUri, request);
using (var response = webRequest.GetResponse())
using (var stream = response.GetResponseStream())
return stream.ReadFully();
}
#else
private void DownloadBytes(string requestUri, object request, Action<byte[]> callback = null)
{
SendRequest(requestUri, request, webRequest => webRequest.BeginGetResponse(delegate(IAsyncResult result)
{
var webReq = (HttpWebRequest)result.AsyncState;
var response = (HttpWebResponse)webReq.EndGetResponse(result);
using (var stream = response.GetResponseStream())
{
var bytes = stream.ReadFully();
if (callback != null)
{
callback(bytes);
}
}
}, null));
}
#endif
public void SendOneWay(object request)
{
var requestUri = this.AsyncOneWayBaseUri.WithTrailingSlash() + request.GetType().Name;
DownloadBytes(requestUri, request);
}
public void SendOneWay(string relativeOrAbsoluteUrl, object request)
{
var requestUri = GetUrl(relativeOrAbsoluteUrl);
DownloadBytes(requestUri, request);
}
public void SendAsync<TResponse>(object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
var requestUri = this.SyncReplyBaseUri.WithTrailingSlash() + request.GetType().Name;
asyncClient.SendAsync(Web.HttpMethod.Post, requestUri, request, onSuccess, onError);
}
public void GetAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
asyncClient.SendAsync(Web.HttpMethod.Get, GetUrl(relativeOrAbsoluteUrl), null, onSuccess, onError);
}
public void DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
asyncClient.SendAsync(Web.HttpMethod.Delete, GetUrl(relativeOrAbsoluteUrl), null, onSuccess, onError);
}
public void PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
asyncClient.SendAsync(Web.HttpMethod.Post, GetUrl(relativeOrAbsoluteUrl), request, onSuccess, onError);
}
public void PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
asyncClient.SendAsync(Web.HttpMethod.Put, GetUrl(relativeOrAbsoluteUrl), request, onSuccess, onError);
}
#if !SILVERLIGHT
public virtual TResponse Send<TResponse>(string httpMethod, string relativeOrAbsoluteUrl, object request)
{
var requestUri = GetUrl(relativeOrAbsoluteUrl);
var client = SendRequest(httpMethod, requestUri, request);
try
{
using (var responseStream = client.GetResponse().GetResponseStream())
{
var response = DeserializeFromStream<TResponse>(responseStream);
return response;
}
}
catch (Exception ex)
{
TResponse response;
if (!HandleResponseException(ex, httpMethod, requestUri, request, out response))
{
throw;
}
return response;
}
}
public TResponse Get<TResponse>(string relativeOrAbsoluteUrl)
{
return Send<TResponse>(Web.HttpMethod.Get, relativeOrAbsoluteUrl, null);
}
public TResponse Delete<TResponse>(string relativeOrAbsoluteUrl)
{
return Send<TResponse>(Web.HttpMethod.Delete, relativeOrAbsoluteUrl, null);
}
public TResponse Post<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return Send<TResponse>(Web.HttpMethod.Post, relativeOrAbsoluteUrl, request);
}
public TResponse Put<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return Send<TResponse>(Web.HttpMethod.Put, relativeOrAbsoluteUrl, request);
}
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, string mimeType)
{
var requestUri = GetUrl(relativeOrAbsoluteUrl);
var webRequest = (HttpWebRequest)WebRequest.Create(requestUri);
webRequest.Method = Web.HttpMethod.Post;
webRequest.Accept = ContentType;
if (Proxy != null) webRequest.Proxy = Proxy;
try
{
if (HttpWebRequestFilter != null)
{
HttpWebRequestFilter(webRequest);
}
var webResponse = webRequest.UploadFile(fileToUpload, mimeType);
using (var responseStream = webResponse.GetResponseStream())
{
var response = DeserializeFromStream<TResponse>(responseStream);
return response;
}
}
catch (Exception ex)
{
HandleResponseException<TResponse>(ex, requestUri);
throw;
}
}
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType)
{
var requestUri = GetUrl(relativeOrAbsoluteUrl);
var webRequest = (HttpWebRequest)WebRequest.Create(requestUri);
webRequest.Method = Web.HttpMethod.Post;
webRequest.Accept = ContentType;
if (Proxy != null) webRequest.Proxy = Proxy;
try
{
if (HttpWebRequestFilter != null)
{
HttpWebRequestFilter(webRequest);
}
webRequest.UploadFile(fileToUpload, fileName, mimeType);
var webResponse = webRequest.GetResponse();
using (var responseStream = webResponse.GetResponseStream())
{
var response = DeserializeFromStream<TResponse>(responseStream);
return response;
}
}
catch (Exception ex)
{
HandleResponseException<TResponse>(ex, requestUri);
throw;
}
}
#endif
public void Dispose() { }
}
}