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
827 lines (714 loc) · 30.9 KB
/
ServiceClientBase.cs
File metadata and controls
827 lines (714 loc) · 30.9 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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
using System;
using System.IO;
using System.Net;
#if !(MONOTOUCH || SILVERLIGHT)
using System.Web;
#endif
using ServiceStack.Common;
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>
private static Action<HttpWebRequest> httpWebRequestFilter;
public static Action<HttpWebRequest> HttpWebRequestFilter
{
get
{
return httpWebRequestFilter;
}
set
{
httpWebRequestFilter = value;
AsyncServiceClient.HttpWebRequestFilter = value;
}
}
/// <summary>
/// The response action is called once the server response is available.
/// It will allow you to access raw response information.
/// This response action is executed globally.
/// Note that you should NOT consume the response stream as this is handled by ServiceStack
/// </summary>
private static Action<HttpWebResponse> httpWebResponseFilter;
public static Action<HttpWebResponse> HttpWebResponseFilter
{
get
{
return httpWebResponseFilter;
}
set
{
httpWebResponseFilter = value;
AsyncServiceClient.HttpWebResponseFilter = value;
}
}
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,
UserName = this.UserName,
Password = this.Password,
LocalHttpWebRequestFilter = this.LocalHttpWebRequestFilter,
LocalHttpWebResponseFilter = this.LocalHttpWebResponseFilter
};
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;
}
/// <summary>
/// Sets all baseUri properties, using the Format property for the SyncReplyBaseUri and AsyncOneWayBaseUri
/// </summary>
/// <param name="baseUri">Base URI of the service</param>
public void SetBaseUri(string baseUri)
{
this.BaseUri = baseUri;
this.asyncClient.BaseUri = baseUri;
this.SyncReplyBaseUri = baseUri.WithTrailingSlash() + Format + "/syncreply/";
this.AsyncOneWayBaseUri = baseUri.WithTrailingSlash() + Format + "/asynconeway/";
}
/// <summary>
/// Sets all baseUri properties allowing for a temporary override of the Format property
/// </summary>
/// <param name="baseUri">Base URI of the service</param>
/// <param name="format">Override of the Format property for the service</param>
//Marked obsolete on 4/11/2012
[Obsolete("Please call the SetBaseUri(string baseUri) method, which uses the specific implementation's Format property.")]
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/";
}
private bool _disableAutoCompression;
/// <summary>
/// Whether to Accept Gzip,Deflate Content-Encoding and to auto decompress responses
/// </summary>
public bool DisableAutoCompression
{
get { return _disableAutoCompression; }
set
{
_disableAutoCompression = value;
asyncClient.DisableAutoCompression = value;
}
}
private string _username;
/// <summary>
/// The user name for basic authentication
/// </summary>
public string UserName
{
get { return _username; }
set
{
_username = value;
asyncClient.UserName = value;
}
}
private string _password;
/// <summary>
/// The password for basic authentication
/// </summary>
public string Password
{
get { return _password; }
set
{
_password = value;
asyncClient.Password = value;
}
}
/// <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 abstract string Format { get; }
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>
/// Called before request resend, when the initial request required authentication
/// </summary>
private Action<WebRequest> onAuthenticationRequired { get; set; }
public Action<WebRequest> OnAuthenticationRequired
{
get
{
return onAuthenticationRequired;
}
set
{
onAuthenticationRequired = value;
asyncClient.OnAuthenticationRequired = value;
}
}
/// <summary>
/// The request filter is called before any request.
/// This request filter only works with the instance where it was set (not global).
/// </summary>
private Action<HttpWebRequest> localHttpWebRequestFilter { get; set; }
public Action<HttpWebRequest> LocalHttpWebRequestFilter
{
get
{
return localHttpWebRequestFilter;
}
set
{
localHttpWebRequestFilter = value;
asyncClient.LocalHttpWebRequestFilter = value;
}
}
/// <summary>
/// The response action is called once the server response is available.
/// It will allow you to access raw response information.
/// Note that you should NOT consume the response stream as this is handled by ServiceStack
/// </summary>
private Action<HttpWebResponse> localHttpWebResponseFilter { get; set; }
public Action<HttpWebResponse> LocalHttpWebResponseFilter
{
get
{
return localHttpWebResponseFilter;
}
set
{
localHttpWebResponseFilter = value;
asyncClient.LocalHttpWebResponseFilter = value;
}
}
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
{
var webResponse = client.GetResponse();
return HandleResponse<TResponse>(webResponse);
}
catch (Exception ex)
{
TResponse response;
if (!HandleResponseException(ex, requestUri, () => SendRequest(Web.HttpMethod.Post, requestUri, request), c => c.GetResponse(), out response))
{
throw;
}
return response;
}
}
private bool HandleResponseException<TResponse>(Exception ex, string requestUri, Func<WebRequest> createWebRequest, Func<WebRequest, WebResponse> getResponse, out TResponse response)
{
try
{
if (WebRequestUtils.ShouldAuthenticate(ex, this.UserName, this.Password))
{
var client = createWebRequest();
client.AddBasicAuth(this.UserName, this.Password);
if (OnAuthenticationRequired != null)
{
OnAuthenticationRequired(client);
}
var webResponse = getResponse(client);
response = HandleResponse<TResponse>(webResponse);
return true;
}
}
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)
{
return PrepareWebRequest(httpMethod, requestUri, request, client =>
{
using (var requestStream = client.GetRequestStream())
{
SerializeToStream(null, request, requestStream);
}
});
}
private WebRequest PrepareWebRequest(string httpMethod, string requestUri, object request, Action<HttpWebRequest> sendRequestAction)
{
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 (!DisableAutoCompression)
{
client.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
client.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
if (StoreCookies)
{
client.CookieContainer = CookieContainer;
}
ApplyWebRequestFilters(client);
if (httpMethod != Web.HttpMethod.Get
&& httpMethod != Web.HttpMethod.Delete)
{
client.ContentType = ContentType;
if (sendRequestAction != null) sendRequestAction(client);
}
}
catch (AuthenticationException ex)
{
throw WebRequestUtils.CreateCustomException(requestUri, ex) ?? ex;
}
return client;
}
private void ApplyWebResponseFilters(WebResponse webResponse)
{
if (!(webResponse is HttpWebResponse)) return;
if (HttpWebResponseFilter != null)
HttpWebResponseFilter((HttpWebResponse)webResponse);
if (LocalHttpWebResponseFilter != null)
LocalHttpWebResponseFilter((HttpWebResponse)webResponse);
}
private void ApplyWebRequestFilters(HttpWebRequest client)
{
if (LocalHttpWebRequestFilter != null)
LocalHttpWebRequestFilter(client);
if (HttpWebRequestFilter != null)
HttpWebRequestFilter(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.CombineWith(relativeOrAbsoluteUrl);
}
#if !SILVERLIGHT
private byte[] DownloadBytes(string requestUri, object request)
{
var webRequest = SendRequest(requestUri, request);
using (var response = webRequest.GetResponse())
{
ApplyWebResponseFilters(response);
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 virtual void SendOneWay(object request)
{
var requestUri = this.AsyncOneWayBaseUri.WithTrailingSlash() + request.GetType().Name;
DownloadBytes(requestUri, request);
}
public virtual void SendOneWay(string relativeOrAbsoluteUrl, object request)
{
var requestUri = GetUrl(relativeOrAbsoluteUrl);
DownloadBytes(requestUri, request);
}
public virtual 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 virtual void GetAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
asyncClient.SendAsync(Web.HttpMethod.Get, GetUrl(relativeOrAbsoluteUrl), null, onSuccess, onError);
}
public virtual void DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
asyncClient.SendAsync(Web.HttpMethod.Delete, GetUrl(relativeOrAbsoluteUrl), null, onSuccess, onError);
}
public virtual 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 virtual void PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
asyncClient.SendAsync(Web.HttpMethod.Put, GetUrl(relativeOrAbsoluteUrl), request, onSuccess, onError);
}
public virtual void CancelAsync()
{
asyncClient.CancelAsync();
}
#if !SILVERLIGHT
public virtual TResponse Send<TResponse>(string httpMethod, string relativeOrAbsoluteUrl, object request)
{
var requestUri = GetUrl(relativeOrAbsoluteUrl);
var client = SendRequest(httpMethod, requestUri, request);
try
{
var webResponse = client.GetResponse();
return HandleResponse<TResponse>(webResponse);
}
catch (Exception ex)
{
TResponse response;
if (!HandleResponseException(ex, requestUri, () => SendRequest(httpMethod, requestUri, request), c => c.GetResponse(), out response))
{
throw;
}
return response;
}
}
public virtual TResponse Get<TResponse>(string relativeOrAbsoluteUrl)
{
return Send<TResponse>(Web.HttpMethod.Get, relativeOrAbsoluteUrl, null);
}
public virtual TResponse Delete<TResponse>(string relativeOrAbsoluteUrl)
{
return Send<TResponse>(Web.HttpMethod.Delete, relativeOrAbsoluteUrl, null);
}
public virtual TResponse Post<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return Send<TResponse>(Web.HttpMethod.Post, relativeOrAbsoluteUrl, request);
}
public virtual TResponse Put<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return Send<TResponse>(Web.HttpMethod.Put, relativeOrAbsoluteUrl, request);
}
public virtual TResponse Patch<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return Send<TResponse>(Web.HttpMethod.Patch, relativeOrAbsoluteUrl, request);
}
public virtual TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, object request)
{
return PostFileWithRequest<TResponse>(relativeOrAbsoluteUrl, fileToUpload.OpenRead(), fileToUpload.Name, request);
}
public virtual TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, object request)
{
var requestUri = GetUrl(relativeOrAbsoluteUrl);
var currentStreamPosition = fileToUpload.Position;
Func<WebRequest> createWebRequest = () => {
var webRequest = PrepareWebRequest(Web.HttpMethod.Post, requestUri, null, null);
var queryString = QueryStringSerializer.SerializeToString(request);
#if !MONOTOUCH
var nameValueCollection = HttpUtility.ParseQueryString(queryString);
#endif
var boundary = DateTime.Now.Ticks.ToString();
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
boundary = "--" + boundary;
var newLine = Environment.NewLine;
using (var outputStream = webRequest.GetRequestStream())
{
#if !MONOTOUCH
foreach (var key in nameValueCollection.AllKeys)
{
outputStream.Write(boundary + newLine);
outputStream.Write("Content-Disposition: form-data;name=\"{0}\"{1}{2}".FormatWith(key, newLine, newLine));
outputStream.Write(nameValueCollection[key] + newLine);
}
#endif
outputStream.Write(boundary + newLine);
outputStream.Write("Content-Disposition: form-data;name=\"{0}\";filename=\"{1}\"{2}{3}".FormatWith("upload", fileName, newLine, newLine));
var buffer = new byte[4096];
int byteCount;
while ((byteCount = fileToUpload.Read(buffer, 0, 4096)) > 0)
{
outputStream.Write(buffer, 0, byteCount);
}
outputStream.Write(newLine);
outputStream.Write(boundary + "--");
}
return webRequest;
};
try
{
var webRequest = createWebRequest();
var webResponse = webRequest.GetResponse();
return HandleResponse<TResponse>(webResponse);
}
catch (Exception ex)
{
TResponse response;
// restore original position before retry
fileToUpload.Seek(currentStreamPosition, SeekOrigin.Begin);
if (!HandleResponseException(ex, requestUri, createWebRequest, c => c.GetResponse(), out response))
{
throw;
}
return response;
}
}
public virtual TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, string mimeType)
{
return PostFile<TResponse>(relativeOrAbsoluteUrl, fileToUpload.OpenRead(), fileToUpload.Name, mimeType);
}
public virtual TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType)
{
var currentStreamPosition = fileToUpload.Position;
var requestUri = GetUrl(relativeOrAbsoluteUrl);
Func<WebRequest> createWebRequest = () => PrepareWebRequest(Web.HttpMethod.Post, requestUri, null, null);
try
{
var webRequest = createWebRequest();
webRequest.UploadFile(fileToUpload, fileName, mimeType);
var webResponse = webRequest.GetResponse();
return HandleResponse<TResponse>(webResponse);
}
catch (Exception ex)
{
TResponse response;
// restore original position before retry
fileToUpload.Seek(currentStreamPosition, SeekOrigin.Begin);
if (!HandleResponseException(ex, requestUri, createWebRequest, c => { c.UploadFile(fileToUpload, fileName, mimeType); return c.GetResponse(); }, out response))
{
throw;
}
return response;
}
}
private TResponse HandleResponse<TResponse>(WebResponse webResponse)
{
ApplyWebResponseFilters(webResponse);
using (var responseStream = webResponse.GetResponseStream())
{
var response = DeserializeFromStream<TResponse>(responseStream);
return response;
}
}
#endif
public void Dispose() { }
}
}