如何将HTTP标头添加到SOAP客户端

时间:2013-09-19 05:16:02

标签: c# windows-8 soap-client

如果可以将HTTP标头添加到soap客户端Web服务调用,有人可以回答我。 在浏览互联网之后,我发现的唯一薄片是如何添加SOAP标头。

代码如下所示:

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

更新

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>

信封中的标题属性应为空

4 个答案:

答案 0 :(得分:27)

尝试使用它:

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();
}

有关详细信息,请参阅here

答案 1 :(得分:1)

试试这个

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();
}

答案 2 :(得分:0)

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

答案 3 :(得分:0)

其中一些答案会向请求的 XML 正文内容添加标头。要将标头添加到请求本身,请执行以下操作:

SoapServiceClient client = new SoapServiceClient();

using(var scope = new OperationContextScope(client.InnerChannel)) 
{
     WebOperationContext.Current.OutgoingRequest.Headers.
           Add("headerKey", "headerValue");

    var result = client.MyClientMethod();
}

注意 WebOperationContext 的 OperationContext 的变化。是一个帮助器类,可提供对 Web 请求和响应的上下文属性的轻松访问。