forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWcfServiceClient.cs
More file actions
424 lines (364 loc) · 15.1 KB
/
WcfServiceClient.cs
File metadata and controls
424 lines (364 loc) · 15.1 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
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using ServiceStack.Common.Utils;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.ServiceModel;
namespace ServiceStack.ServiceClient.Web
{
/// <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)
{
return;
}
/// <summary>
/// Adds the singleton of the <see cref="ClientIdentityMessageInspector"/> 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)
{
return;
}
public void Validate(ServiceEndpoint endpoint)
{
return;
}
}
/// <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 CookieContainer cookieContainer;
public string Uri { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ClientIdentityMessageInspector"/> 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="ClientIdentityMessageInspector" /> instance.
/// </summary>
public static CookieManagerMessageInspector Instance
{
get
{
if (instance == null)
{
instance = new CookieManagerMessageInspector();
}
return instance;
}
}
/// <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)
{
HttpResponseMessageProperty httpResponse =
reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
if (httpResponse != null)
{
string 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)
{
HttpRequestMessageProperty httpRequest;
// 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());
}
httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookieContainer.GetCookieHeader(new System.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 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 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(string.Format("SOAP FAULT '{0}': {1}", errMsg, node.InnerXml), e);
}
return e;
}
private ServiceEndpoint SyncReply
{
get
{
var contract = new ContractDescription("ServiceStack.ServiceClient.Web.ISyncReply", "http://services.servicestack.net/");
var addr = new EndpointAddress(Uri);
var endpoint = new ServiceEndpoint(contract, Binding, addr);
return endpoint;
}
}
public Message Send(object 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)
{
try
{
var responseMsg = Send(request);
var response = responseMsg.GetBody<T>();
var responseStatus = GetResponseStatus(response);
if (responseStatus != null && !string.IsNullOrEmpty(responseStatus.ErrorCode))
{
throw new WebServiceException(responseStatus.Message, null) {
StatusCode = 500,
ResponseDto = response,
StatusDescription = responseStatus.Message,
};
}
return response;
}
catch (WebServiceException webEx)
{
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
};
}
}
public TResponse Send<TResponse>(IReturn<TResponse> request)
{
return Send<TResponse>((object)request);
}
public void Send(IReturnVoid request)
{
throw new NotImplementedException();
}
public ResponseStatus GetResponseStatus(object response)
{
if (response == null)
return null;
var hasResponseStatus = response as IHasResponseStatus;
if (hasResponseStatus != null)
return hasResponseStatus.ResponseStatus;
var propertyInfo = response.GetType().GetProperty("ResponseStatus");
if (propertyInfo == null)
return null;
return ReflectionUtils.GetProperty(response, propertyInfo) as ResponseStatus;
}
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, string mimeType)
{
throw new NotImplementedException();
}
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType)
{
throw new NotImplementedException();
}
public void SendOneWay(object request)
{
SendOneWay(request, request.GetType().Name);
}
public void SendOneWay(string relativeOrAbsoluteUrl, object request)
{
SendOneWay(Message.CreateMessage(MessageVersion, relativeOrAbsoluteUrl, request));
}
public void SendOneWay(object request, string action)
{
SendOneWay(Message.CreateMessage(MessageVersion, action, request));
}
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 SendAsync<TResponse>(object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void SetCredentials(string userName, string password)
{
throw new NotImplementedException();
}
public void GetAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void GetAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void DeleteAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void PostAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void PutAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void CustomMethodAsync<TResponse>(string httpVerb, IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void CancelAsync()
{
throw new NotImplementedException();
}
public void Dispose()
{
}
public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, object request)
{
throw new NotImplementedException();
}
public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, object request)
{
throw new NotImplementedException();
}
}
}
#endif