Need help with manipulating SOAP header in my WCF client before sending request

前端 未结 1 1211
春和景丽
春和景丽 2021-01-19 05:41

I have a unique requirement where I need to send a highly customized soap header in a request to a external vendor. The only way my WCF client can interact with their web s

相关标签:
1条回答
  • 2021-01-19 06:15

    Check out the following article which shows you an example of how to implement an IClientMessageInspector which alters the message and injects a custom header.

    Handling custom SOAP headers via WCF Behaviors

    First you need to define a custom header to represent the contents of a SOAP header. To do so create your own descendant of the MessageHeader class.

    public class MyHeader : MessageHeader
    { 
        //... 
    }
    

    Create an IClientMessageInspector implementation that injects your custom header just before sending the request (BeforeSendRequest).

    public class CustomMessageInspector : IClientMessageInspector
    {
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
            request = buffer.CreateMessage();
            request.Headers.Add(new MyHeader());
            return null;
        }
    
        //...
    }
    

    Now you need to add your custom message inspector to the WCF pipeline, but you already got this part covered.

    The Message parameter of the BeforeSendRequest(ref Message request, IClientChannel channel) can be used to read the SOAP message using one of the methods of the Message type (ToString(), GetBody(), GetReaderAtBodyContents()...etc.).

    To get the body of the message use the GetReaderAtBodyContents() method which returns an XmlDictionaryReader object. Use this XML reader to retrieve the body as a string.

    For example:

    using (XmlDictionaryReader reader = message.GetReaderAtBodyContents())
    {
        string content = reader.ReadOuterXml();
        //...   
    }
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题