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
382 lines (319 loc) · 11.3 KB
/
ServiceClientBase.cs
File metadata and controls
382 lines (319 loc) · 11.3 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
using System;
using System.IO;
using System.Net;
using System.Security.Authentication;
using System.Text;
using ServiceStack.Common.Web;
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
: IServiceClient, IRestClient
{
private static readonly ILog log = LogManager.GetLogger(typeof(ServiceClientBase));
public static Action<HttpWebRequest> HttpWebRequestFilter { get; set; }
public const string DefaultHttpMethod = "POST";
readonly AsyncServiceClient asyncClient;
protected ServiceClientBase()
{
this.HttpMethod = DefaultHttpMethod;
asyncClient = new AsyncServiceClient {
ContentType = ContentType,
StreamSerializer = SerializeToStream,
StreamDeserializer = StreamDeserializer
};
}
protected ServiceClientBase(string syncReplyBaseUri, string asyncOneWayBaseUri)
: this()
{
this.SyncReplyBaseUri = syncReplyBaseUri;
this.AsyncOneWayBaseUri = asyncOneWayBaseUri;
}
public void SetBaseUri(string baseUri, string format)
{
this.BaseUri = baseUri;
this.SyncReplyBaseUri = baseUri.WithTrailingSlash() + format + "/syncreply/";
this.AsyncOneWayBaseUri = baseUri.WithTrailingSlash() + format + "/asynconeway/";
}
public string UserName { get; set; }
public string Password { get; set; }
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; }
public IWebProxy Proxy { get; set; }
private ICredentials credentials;
public ICredentials Credentials
{
set
{
this.credentials = value;
this.asyncClient.Credentials = value;
}
}
public abstract void SerializeToStream(IRequestContext requestContext, object request, Stream stream);
public abstract T DeserializeFromStream<T>(Stream stream);
public abstract StreamDeserializerDelegate StreamDeserializer { get; }
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);
using (var responseStream = client.GetResponse().GetResponseStream())
{
response = DeserializeFromStream<TResponse>(responseStream);
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,
};
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,
};
}
//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)
{
var isHttpGet = HttpMethod != null && HttpMethod.ToUpper() == "GET";
if (isHttpGet)
{
var queryString = QueryStringSerializer.SerializeToString(request);
if (!string.IsNullOrEmpty(queryString))
{
requestUri += "?" + queryString;
}
}
return SendRequest(HttpMethod ?? DefaultHttpMethod, requestUri, request);
}
private WebRequest SendRequest(string httpMethod, string requestUri, object request)
{
if (httpMethod == null)
throw new ArgumentNullException("httpMethod");
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 (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;
}
private string GetUrl(string relativeOrAbsoluteUrl)
{
return relativeOrAbsoluteUrl.StartsWith("http:")
|| relativeOrAbsoluteUrl.StartsWith("https:")
? relativeOrAbsoluteUrl
: this.BaseUri + relativeOrAbsoluteUrl;
}
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();
}
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);
}
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
{
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 void Dispose() { }
}
}