Исходный код вики Перехват текста сообщений

Редактировал(а) Alexandr Fokin 2023/01/05 20:56

Последние авторы
1 Реализация перехвата сообщений, отправленных и полученных клиентом.
2 Также можно реализовать общую обертку над всеми клиентами, предоставляющую интерфейс перехвата
3
4 {{code language="C#"}}
5 using System.ServiceModel;
6 using System.ServiceModel.Dispatcher;
7 using System.ServiceModel.Description;
8 using System.ServiceModel.Channels;
9
10 namespace Test
11 {
12 class MessageBehavior
13 : IClientMessageInspector,
14 IEndpointBehavior
15 {
16 public Action<string> OnSend { get; set; }
17 public Action<string> OnReceive { get; set; }
18
19
20 public void AddBindingParameters(
21 ServiceEndpoint endpoint,
22 BindingParameterCollection bindingParameters
23 )
24 {
25 }
26
27 public void ApplyClientBehavior(
28 ServiceEndpoint endpoint,
29 ClientRuntime clientRuntime
30 )
31 {
32 clientRuntime
33 .ClientMessageInspectors
34 .Add(this);
35 }
36
37 public void ApplyDispatchBehavior(
38 ServiceEndpoint endpoint,
39 EndpointDispatcher endpointDispatcher
40 )
41 {
42 }
43
44 public void Validate(
45 ServiceEndpoint endpoint
46 )
47 {
48 }
49
50
51 public object BeforeSendRequest(
52 ref Message request,
53 IClientChannel channel
54 )
55 {
56 OnSend?.Invoke(
57 request.ToString()
58 );
59 return null;
60 }
61
62 public void AfterReceiveReply(
63 ref Message reply,
64 object correlationState
65 )
66 {
67 OnReceive?.Invoke(
68 reply.ToString()
69 );
70 }
71 }
72
73
74 static class Test
75 {
76 static void RunTest()
77 {
78 using (Service1Client client = new Service1Client())
79 {
80 client
81 .Endpoint
82 .EndpointBehaviors
83 .Add(
84 new MessageBehavior()
85 {
86 OnReceive = OnMsg,
87 OnSend = OnMsg
88 }
89 );
90
91 var res = client.GetData(123);
92 }
93 }
94 }
95 }
96 {{/code}}
97
98 ----
99
100 ссылки:
101
102 WCF Client Request / Response Message Inspection
103 http://developereventlog.blogspot.com/2012/07/wcf-client-request-response-message.html
104
105 IClientMessageInspector Интерфейс
106 https://docs.microsoft.com/ru-ru/dotnet/api/system.servicemodel.dispatcher.iclientmessageinspector?view=dotnet-uwp-10.0
107
108 ClientRuntime Класс
109 https://docs.microsoft.com/ru-ru/dotnet/api/system.servicemodel.dispatcher.clientruntime?view=netframework-4.8
110
111
112 **SoapHttpClientProtocol**
113
114 Получение текста запросов из SoapHttpClientProtocol
115 https://habr.com/ru/post/337672/
116
117 Getting the raw SOAP XML sent via SoapHttpClientProtocol
118 https://orbinary.com/blog/2010/01/getting-the-raw-soap-xml-sent-via-soaphttpclientprotocol/