Skip to content

Instantly share code, notes, and snippets.

@skenderbeu
Last active June 11, 2018 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skenderbeu/20832a44ee52b01fb249a9973adbd787 to your computer and use it in GitHub Desktop.
Save skenderbeu/20832a44ee52b01fb249a9973adbd787 to your computer and use it in GitHub Desktop.
using System;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.IO;
namespace RoyalMail
{
/// <summary>
/// Used - https://blogs.msdn.microsoft.com/mohamedg/2012/12/13/adding-http-headers-to-wcf-calls/
/// </summary>
public class ClientMessageInspector : IClientMessageInspector
{
RoyalMailHeaderCredentials _credentials;
public void SetCredentials(RoyalMailHeaderCredentials credentials)
{
_credentials = credentials;
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
SetMessagePropertyHeaders(request);
var guid = Guid.NewGuid();
RequestMessage requestMessage = new RequestMessage(guid);
requestMessage.WriteLog(ref request);
return guid;;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
ResponseMessage responseMessage = new ResponseMessage((Guid)correlationState);
responseMessage.WriteLog(ref reply);
}
private void SetMessagePropertyHeaders(Message request)
{
if (_credentials == null) return;
if (request.Properties.TryGetValue(
HttpRequestMessageProperty.Name, out object httpRequestMessageObject))
{
if (!(httpRequestMessageObject is HttpRequestMessageProperty property))
throw new ArgumentNullException(nameof(property));
SetHeaders(property);
}
else
{
HttpRequestMessageProperty property = new HttpRequestMessageProperty();
SetHeaders(property);
request.Properties.Add(HttpRequestMessageProperty.Name, property);
}
}
private void SetHeaders(HttpRequestMessageProperty property)
{
property.Headers["Accept"] = "application/soap+xml";
property.Headers["X-IBM-Client-Id"] = _credentials.ClientID;
property.Headers["X-IBM-Client-Secret"] = _credentials.Secret;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment