How to add HTTP Header to SOAP Client

允我心安 提交于 2019-11-26 17:14:47

问题


Can someone answer me if it is possible to add HTTP header to soap client web-service calls. After surfing Internet the only thin I found was how to add SOAP header.

The code looks like this:

var client =new MyServiceSoapClient();
//client.AddHttpHeader("myCustomHeader","myValue");//There's no such method, it's just for clearness
var res = await client.MyMethod();

UPDATE:

The request should look like this
POST https://service.com/Service.asmx HTTP/1.1
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://www.host.com/schemas/Authentication.xsd/Action"
Content-Length: 351
MyHeader: "myValue"
Expect: 100-continue
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header/>
  <s:Body>
    <myBody>BodyGoesHere</myBody>
  </s:Body>
</s:Envelope>

Header property in the envelop should be empty


回答1:


Try to use this:

SoapServiceClient client = new SoapServiceClient();

using(new OperationContextScope(client.InnerChannel)) 
{
    // // Add a SOAP Header (Header property in the envelope) to an outgoing request. 
    // MessageHeader aMessageHeader = MessageHeader
    //    .CreateHeader("MySOAPHeader", "http://tempuri.org", "MySOAPHeaderValue");
    // OperationContext.Current.OutgoingMessageHeaders.Add(aMessageHeader);

    // Add a HTTP Header to an outgoing request
    HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
    requestMessage.Headers["MyHttpHeader"] = "MyHttpHeaderValue";
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] 
       = requestMessage;

    var result = client.MyClientMethod();
}

See here for more detail.




回答2:


Try this

var client = new MyServiceSoapClient();
using (var scope = new OperationContextScope(client.InnerChannel))
{
    // Create a custom soap header
    var msgHeader = MessageHeader.CreateHeader("myCustomHeader", "The_namespace_URI_of_the_header_XML_element", "myValue");
    // Add the header into request message
    OperationContext.Current.OutgoingMessageHeaders.Add(msgHeader);

    var res = await client.MyMethod();
}



回答3:


var client = new MyServiceSoapClient();
using (new OperationContextScope(InnerChannel))
{ 
    WebOperationContext.Current.OutgoingRequest.Headers.Add("myCustomHeader", "myValue");                
}


来源:https://stackoverflow.com/questions/18886660/how-to-add-http-header-to-soap-client

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