/
WcfServiceClient.cs
624 lines (505 loc) · 23.3 KB
/
WcfServiceClient.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
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
#if NETFX
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Xml;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Threading;
using ServiceStack.Serialization;
namespace ServiceStack
{
/// <summary>
/// Adds the singleton instance of <see cref="CookieManagerMessageInspector"/> to an endpoint on the client.
/// </summary>
/// <remarks>
/// Based on http://megakemp.wordpress.com/2009/02/06/managing-shared-cookies-in-wcf/
/// </remarks>
public class CookieManagerEndpointBehavior : IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) {}
/// <summary>
/// Adds the singleton of the <see cref="CookieManagerMessageInspector"/> class to the client endpoint's message inspectors.
/// </summary>
/// <param name="endpoint">The endpoint that is to be customized.</param>
/// <param name="clientRuntime">The client runtime to be customized.</param>
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
var cm = CookieManagerMessageInspector.Instance;
cm.Uri = endpoint.ListenUri.AbsoluteUri;
clientRuntime.MessageInspectors.Add(cm);
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) {}
public void Validate(ServiceEndpoint endpoint) {}
}
/// <summary>
/// Maintains a copy of the cookies contained in the incoming HTTP response received from any service
/// and appends it to all outgoing HTTP requests.
/// </summary>
/// <remarks>
/// This class effectively allows to send any received HTTP cookies to different services,
/// reproducing the same functionality available in ASMX Web Services proxies with the <see cref="System.Net.CookieContainer"/> class.
/// Based on http://megakemp.wordpress.com/2009/02/06/managing-shared-cookies-in-wcf/
/// </remarks>
public class CookieManagerMessageInspector : IClientMessageInspector
{
private static CookieManagerMessageInspector instance;
private readonly CookieContainer cookieContainer;
public string Uri { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="CookieManagerMessageInspector"/> class.
/// </summary>
public CookieManagerMessageInspector()
{
cookieContainer = new CookieContainer();
Uri = "http://tempuri.org";
}
public CookieManagerMessageInspector(string uri)
{
cookieContainer = new CookieContainer();
Uri = uri;
}
/// <summary>
/// Gets the singleton <see cref="CookieManagerMessageInspector" /> instance.
/// </summary>
public static CookieManagerMessageInspector Instance =>
instance ??= new CookieManagerMessageInspector();
/// <summary>
/// Inspects a message after a reply message is received but prior to passing it back to the client application.
/// </summary>
/// <param name="reply">The message to be transformed into types and handed back to the client application.</param>
/// <param name="correlationState">Correlation state data.</param>
public void AfterReceiveReply(ref Message reply, object correlationState)
{
var httpResponse = reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
var cookie = httpResponse?.Headers[HttpResponseHeader.SetCookie];
if (!string.IsNullOrEmpty(cookie))
{
cookieContainer.SetCookies(new System.Uri(Uri), cookie);
}
}
/// <summary>
/// Inspects a message before a request message is sent to a service.
/// </summary>
/// <param name="request">The message to be sent to the service.</param>
/// <param name="channel">The client object channel.</param>
/// <returns>
/// <strong>Null</strong> since no message correlation is used.
/// </returns>
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
// The HTTP request object is made available in the outgoing message only when
// the Visual Studio Debugger is attacched to the running process
if (!request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
{
request.Properties.Add(HttpRequestMessageProperty.Name, new HttpRequestMessageProperty());
}
var httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookieContainer.GetCookieHeader(new Uri(Uri)));
return null;
}
}
public abstract class WcfServiceClient : IWcfServiceClient
{
const string XPATH_SOAP_FAULT = "/s:Fault";
const string XPATH_SOAP_FAULT_REASON = "/s:Fault/s:Reason";
const string NAMESPACE_SOAP = "http://www.w3.org/2003/05/soap-envelope";
const string NAMESPACE_SOAP_ALIAS = "s";
public string WsdlServiceNamespace = "http://schemas.servicestack.net/types";
public string Uri { get; set; }
public abstract void SetProxy(Uri proxyAddress);
protected abstract MessageVersion MessageVersion { get; }
protected abstract Binding Binding { get; }
/// <summary>
/// Specifies if cookies should be stored
/// </summary>
// CCB Custom
public bool StoreCookies { get; set; }
public int Version { get; set; }
public string SessionId { get; set; }
public string BearerToken { get; set; }
protected WcfServiceClient()
{
// CCB Custom
this.StoreCookies = true;
}
private static XmlNamespaceManager GetNamespaceManager(XmlDocument doc)
{
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace(NAMESPACE_SOAP_ALIAS, NAMESPACE_SOAP);
return nsmgr;
}
private static Exception CreateException(Exception e, XmlReader reader)
{
var doc = new XmlDocument();
doc.Load(reader);
var node = doc.SelectSingleNode(XPATH_SOAP_FAULT, GetNamespaceManager(doc));
if (node != null)
{
string errMsg = null;
var nodeReason = doc.SelectSingleNode(XPATH_SOAP_FAULT_REASON, GetNamespaceManager(doc));
if (nodeReason != null)
{
errMsg = nodeReason.FirstChild.InnerXml;
}
return new Exception($"SOAP FAULT '{errMsg}': {node.InnerXml}", e);
}
return e;
}
private ServiceEndpoint SyncReply
{
get
{
var contract = new ContractDescription("ServiceStack.ISyncReply", "http://services.servicestack.net/");
var addr = new EndpointAddress(Uri);
var endpoint = new ServiceEndpoint(contract, Binding, addr);
return endpoint;
}
}
public Message Send(object request)
{
this.PopulateRequestMetadata(request);
return Send(request, request.GetType().Name);
}
public Message Send(object request, string action)
{
return Send(Message.CreateMessage(MessageVersion, action, request));
}
public Message Send(XmlReader reader, string action)
{
return Send(Message.CreateMessage(MessageVersion, action, reader));
}
public Message Send(Message message)
{
using (var client = new GenericProxy<ISyncReply>(SyncReply))
{
// CCB Custom...add behavior to propagate cookies across SOAP method calls
if (StoreCookies)
client.ChannelFactory.Endpoint.Behaviors.Add(new CookieManagerEndpointBehavior());
var response = client.Proxy.Send(message);
return response;
}
}
public static T GetBody<T>(Message message)
{
var buffer = message.CreateBufferedCopy(int.MaxValue);
try
{
return buffer.CreateMessage().GetBody<T>();
}
catch (Exception ex)
{
throw CreateException(ex, buffer.CreateMessage().GetReaderAtBodyContents());
}
}
public T Send<T>(object request)
{
Message responseMsg = null;
try
{
responseMsg = Send(request);
var requestType = request.GetType();
var responseXml = GetMessageXml(responseMsg);
var useXmlSerializerRequest = requestType.HasAttribute<XmlSerializerFormatAttribute>();
var responseType = responseXml.StartsWith("<ErrorResponse")
? typeof(ErrorResponse)
: typeof(T);
var response = useXmlSerializerRequest
? XmlSerializableSerializer.Instance.DeserializeFromString(responseXml, responseType)
: Serialization.DataContractSerializer.Instance.DeserializeFromString(responseXml, responseType);
var responseStatus = response.GetResponseStatus();
if (!string.IsNullOrEmpty(responseStatus?.ErrorCode))
{
throw new WebServiceException(responseStatus.ErrorCode, null)
{
StatusCode = GetErrorStatus(responseMsg),
ResponseDto = response,
StatusDescription = responseStatus.ErrorCode,
};
}
return (T)response;
}
catch (WebServiceException)
{
throw;
}
catch (Exception ex)
{
var webEx = ex as WebException ?? ex.InnerException as WebException;
if (webEx == null)
{
throw new WebServiceException(ex.Message, ex)
{
StatusCode = 500,
};
}
var httpEx = webEx.Response as HttpWebResponse;
throw new WebServiceException(webEx.Message, webEx)
{
StatusCode = httpEx != null ? (int)httpEx.StatusCode : 500
};
}
}
private static string GetMessageXml(Message requestMsg)
{
string requestXml;
using (var reader = requestMsg.GetReaderAtBodyContents())
{
requestXml = reader.ReadOuterXml();
}
return requestXml;
}
private int GetErrorStatus(Message responseMsg)
{
var errorStatus = 500;
try
{
var statusCode = responseMsg.Headers.GetHeader<string>(
HttpHeaders.XStatus, WsdlServiceNamespace);
if (statusCode != null)
{
int.TryParse(statusCode, out errorStatus);
}
}
catch (Exception) {}
return errorStatus;
}
public TResponse Send<TResponse>(IReturn<TResponse> request)
{
return Send<TResponse>((object)request);
}
public void Send(IReturnVoid request)
{
Send<byte[]>(request);
}
public void Publish(object requestDto)
{
SendOneWay(requestDto);
}
public void PublishAll(IEnumerable<object> requestDtos)
{
throw new NotImplementedException();
}
public List<TResponse> SendAll<TResponse>(IEnumerable<object> requests)
{
throw new NotImplementedException();
}
public void AddHeader(string name, string value)
{
throw new NotImplementedException();
}
public void ClearCookies()
{
throw new NotImplementedException();
}
public Dictionary<string, string> GetCookieValues()
{
return new Dictionary<string, string>();
}
public void SetCookie(string name, string value, TimeSpan? expiresIn = null)
{
throw new NotImplementedException();
}
public void Get(IReturnVoid request)
{
throw new NotImplementedException();
}
public TResponse Get<TResponse>(IReturn<TResponse> requestDto)
{
throw new NotImplementedException();
}
public TResponse Get<TResponse>(object requestDto)
{
throw new NotImplementedException();
}
public TResponse Get<TResponse>(string relativeOrAbsoluteUrl)
{
throw new NotImplementedException();
}
public IEnumerable<TResponse> GetLazy<TResponse>(IReturn<QueryResponse<TResponse>> queryDto)
{
throw new NotImplementedException();
}
public void Delete(IReturnVoid requestDto)
{
throw new NotImplementedException();
}
public TResponse Delete<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
public TResponse Delete<TResponse>(object request)
{
throw new NotImplementedException();
}
public TResponse Delete<TResponse>(string relativeOrAbsoluteUrl)
{
throw new NotImplementedException();
}
public void Post(IReturnVoid requestDto)
{
Send(requestDto);
}
public TResponse Post<TResponse>(IReturn<TResponse> requestDto)
{
return Send(requestDto);
}
public TResponse Post<TResponse>(object requestDto)
{
return Send<TResponse>(requestDto);
}
public TResponse Post<TResponse>(string relativeOrAbsoluteUrl, object request)
{
throw new NotImplementedException();
}
public void Put(IReturnVoid requestDto)
{
throw new NotImplementedException();
}
public TResponse Put<TResponse>(IReturn<TResponse> requestDto)
{
throw new NotImplementedException();
}
public TResponse Put<TResponse>(object requestDto)
{
throw new NotImplementedException();
}
public TResponse Put<TResponse>(string relativeOrAbsoluteUrl, object requestDto)
{
throw new NotImplementedException();
}
public void Patch(IReturnVoid requestDto)
{
throw new NotImplementedException();
}
public TResponse Patch<TResponse>(IReturn<TResponse> requestDto)
{
throw new NotImplementedException();
}
public TResponse Patch<TResponse>(object requestDto)
{
throw new NotImplementedException();
}
public TResponse Patch<TResponse>(string relativeOrAbsoluteUrl, object requestDto)
{
throw new NotImplementedException();
}
public TResponse Send<TResponse>(string httpMethod, string relativeOrAbsoluteUrl, object request)
{
throw new NotImplementedException();
}
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType, string fieldName)
{
throw new NotImplementedException();
}
public void CustomMethod(string httpVerb, IReturnVoid requestDto)
{
throw new NotImplementedException();
}
public TResponse CustomMethod<TResponse>(string httpVerb, IReturn<TResponse> requestDto)
{
throw new NotImplementedException();
}
public TResponse CustomMethod<TResponse>(string httpVerb, object requestDto)
{
throw new NotImplementedException();
}
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType)
{
throw new NotImplementedException();
}
public TResponse PostFileWithRequest<TResponse>(
Stream fileToUpload, string fileName, object request, string fieldName = "file")
{
throw new NotImplementedException();
}
public void SendOneWay(object requestDto)
{
SendOneWay(requestDto, requestDto.GetType().Name);
}
public void SendOneWay(string relativeOrAbsoluteUrl, object request)
{
SendOneWay(Message.CreateMessage(MessageVersion, relativeOrAbsoluteUrl, request));
}
public void SendAllOneWay(IEnumerable<object> requests)
{
throw new NotImplementedException();
}
public void SendOneWay(object requestDto, string action)
{
SendOneWay(Message.CreateMessage(MessageVersion, action, requestDto));
}
public void SendOneWay(XmlReader reader, string action)
{
SendOneWay(Message.CreateMessage(MessageVersion, action, reader));
}
public void SendOneWay(Message message)
{
using var client = new GenericProxy<IOneWay>(SyncReply);
client.Proxy.SendOneWay(message);
}
public void SetCredentials(string userName, string password)
{
throw new NotImplementedException();
}
public Task<TResponse> GetAsync<TResponse>(IReturn<TResponse> requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> GetAsync<TResponse>(object requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> GetAsync<TResponse>(string relativeOrAbsoluteUrl, CancellationToken token = default) => throw new NotImplementedException();
public Task GetAsync(IReturnVoid requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> DeleteAsync<TResponse>(IReturn<TResponse> requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> DeleteAsync<TResponse>(object requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, CancellationToken token = default) => throw new NotImplementedException();
public Task DeleteAsync(IReturnVoid requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> PostAsync<TResponse>(IReturn<TResponse> requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> PostAsync<TResponse>(object requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request, CancellationToken token = default) => throw new NotImplementedException();
public Task PostAsync(IReturnVoid requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> PutAsync<TResponse>(IReturn<TResponse> requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> PutAsync<TResponse>(object requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, CancellationToken token = default) => throw new NotImplementedException();
public Task PutAsync(IReturnVoid requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> PatchAsync<TResponse>(IReturn<TResponse> requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> PatchAsync<TResponse>(object requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task PatchAsync(IReturnVoid requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> SendAsync<TResponse>(string httpMethod, string absoluteUrl, object request, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> CustomMethodAsync<TResponse>(string httpVerb, IReturn<TResponse> requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> CustomMethodAsync<TResponse>(string httpVerb, object requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task CustomMethodAsync(string httpVerb, IReturnVoid requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> CustomMethodAsync<TResponse>(string httpVerb, string relativeOrAbsoluteUrl, object request, CancellationToken token = default) => throw new NotImplementedException();
public void CancelAsync()
{
throw new NotImplementedException();
}
public void Dispose()
{
}
public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, object request, string fieldName = "file")
{
throw new NotImplementedException();
}
public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, object request, string fieldName = "file")
{
throw new NotImplementedException();
}
public TResponse PostFilesWithRequest<TResponse>(object request, IEnumerable<UploadFile> files)
{
throw new NotImplementedException();
}
public TResponse PostFilesWithRequest<TResponse>(string relativeOrAbsoluteUrl, object request, IEnumerable<UploadFile> files)
{
throw new NotImplementedException();
}
public Task<TResponse> SendAsync<TResponse>(object requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<TResponse> SendAsync<TResponse>(IReturn<TResponse> requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task<List<TResponse>> SendAllAsync<TResponse>(IEnumerable<object> requests, CancellationToken token = default) => throw new NotImplementedException();
public Task SendAsync(IReturnVoid requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task PublishAsync(object requestDto, CancellationToken token = default) => throw new NotImplementedException();
public Task PublishAllAsync(IEnumerable<object> requestDtos, CancellationToken token = default) => throw new NotImplementedException();
}
}
#endif