How to add attribute to WCF message header with MessageHeader.CreateHeader() method?

谁说胖子不能爱 提交于 2019-12-10 06:41:29

问题


I am adding a WCF custom header with the following code

 MessageHeader header = MessageHeader.CreateHeader("Key", "ns", "Value");
 OperationContext.Current.OutgoingMessageHeaders.Add(header);

With this I also want to add

    xmlns:wsa="http://www.w3.org/2005/08/addressing"
   wsa:IsReferenceParameter="1"

as an attribute to this Message header.

Is there any way to add above namespace and attribute to the message header?


回答1:


I found solution. We have to Implement custome header, which is inhertied from MessageHeader class.

MessageHeader class does have method OnWriteStartHeader(). We can add xml namespaces in this method.

Also we have to override OnWriteHeaderContents() method and write xml or value we want as MessageHeader.

Once this is ready while adding message header in request.Header.Add() pass object of our custom header class.

Refer following links more details.

http://www.netframeworkdev.com/windows-communication-foundation/messageheader-serializer-how-to-use-attributes-52827.shtml

http://social.msdn.microsoft.com/forums/en-US/wcf/thread/c2a39df8-3943-4c41-acca-6da8e96f0dff




回答2:


Define an XmlSerializable class which serialises to the XML element format you want for your header. Then pass an instance of this class as the value parameter of MessageHeader.CreateHeader.




回答3:


If you use the AddressHeader class it automatically adds the isReferenceParameter attribute. The following extension method to ChannelFactory would do what you wanted.

public static void AddHeader<T>(this ChannelFactory<T> factory, string headerName, string value, string nameSpace)
{
    var endpointAddressBuilder = new EndpointAddressBuilder(factory.Endpoint.Address);
    endpointAddressBuilder.Headers.Add(AddressHeader.CreateAddressHeader(headerName, nameSpace, value));

    factory.Endpoint.Address = endpointAddressBuilder.ToEndpointAddress();
}


来源:https://stackoverflow.com/questions/5228430/how-to-add-attribute-to-wcf-message-header-with-messageheader-createheader-met

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!