Исходный код вики Перехват текста сообщений
Версия 1.1 от Alexandr Fokin на 2020/03/20 16:42
Последние авторы
| author | version | line-number | content |
|---|---|---|---|
| 1 | |||
| 2 | Реализация перехвата всех отправленных и полученных сообщений | ||
| 3 | |||
| 4 | |||
| 5 | {{code language="с#"}} | ||
| 6 | using System.ServiceModel; | ||
| 7 | using System.ServiceModel.Dispatcher; | ||
| 8 | using System.ServiceModel.Description; | ||
| 9 | using System.ServiceModel.Channels; | ||
| 10 | |||
| 11 | class MessageBehavior | ||
| 12 | : IClientMessageInspector, | ||
| 13 | IEndpointBehavior | ||
| 14 | { | ||
| 15 | public Action<string> OnSend { set; get; } | ||
| 16 | public Action<string> OnReceive { set; get; } | ||
| 17 | |||
| 18 | |||
| 19 | public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) | ||
| 20 | { | ||
| 21 | } | ||
| 22 | |||
| 23 | public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) | ||
| 24 | { | ||
| 25 | clientRuntime.ClientMessageInspectors.Add(this); | ||
| 26 | } | ||
| 27 | |||
| 28 | public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) | ||
| 29 | { | ||
| 30 | } | ||
| 31 | |||
| 32 | public void Validate(ServiceEndpoint endpoint) | ||
| 33 | { | ||
| 34 | } | ||
| 35 | |||
| 36 | |||
| 37 | public object BeforeSendRequest(ref Message request, IClientChannel channel) | ||
| 38 | { | ||
| 39 | OnSend?.Invoke(request.ToString()); | ||
| 40 | return null; | ||
| 41 | } | ||
| 42 | |||
| 43 | public void AfterReceiveReply(ref Message reply, object correlationState) | ||
| 44 | { | ||
| 45 | OnReceive?.Invoke(reply.ToString()); | ||
| 46 | } | ||
| 47 | |||
| 48 | { | ||
| 49 | using (Service1Client client = new Service1Client()) | ||
| 50 | { | ||
| 51 | client.Endpoint.EndpointBehaviors.Add( | ||
| 52 | new MessageBehavior() | ||
| 53 | { | ||
| 54 | OnReceive = OnMsg, | ||
| 55 | OnSend = OnMsg | ||
| 56 | }); | ||
| 57 | |||
| 58 | var res = client.GetData(123); | ||
| 59 | } | ||
| 60 | } | ||
| 61 | {{/code}} |