c# web service client: how to add custom header to

2019-09-04 11:20发布

问题:

to access a web service i created a proxy class using visual studio "add service reference". Unfortunatly i have to put in the soap header the followings elements

<soapenv:Header>
  <ser:CF>XXXXXXXXXX</ser:CFSender>
        <ser:Identity xmlns="http://company.org" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
     <ser:AppKey>XXX</ser:AppKey>
     <ser:AppName>XXXX</ser:AppName>
     <ser:Parameter>Y</ser:Parameter>
  </ser:Identity>
 </soapenv:Header>

The proxy generated by visual studio has only che following element as method parameter

<ser:CF>XXXXXXXXXX</ser:CFSender>

but not the identity. I need to put "Identity" element just before the web service invocation programmatically.... i need the simplest solution. I saw in other questions how to put one parameter...but identity is a nested object and i don't know what to do. Anyone can help?

回答1:

Here is the solution, from http://blogs.msdn.com/b/wsdevsol/archive/2014/02/07/adding-custom-messageheader-and-http-header-to-a-wcf-method-call.aspx (use Identity obj instead of userInfo)

using(new OperationContextScope(client.InnerChannel)) {

// We will use a custom class called UserInfo to be passed in as a MessageHeader

UserInfo userInfo = new UserInfo();

userInfo.FirstName = "John";

userInfo.LastName = "Doe";

userInfo.Age = 30;



// Add a SOAP Header to an outgoing request

MessageHeader aMessageHeader = MessageHeader.CreateHeader("UserInfo", "http://tempuri.org", userInfo);

OperationContext.Current.OutgoingMessageHeaders.Add(aMessageHeader);