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

kap*_*pie 12 c# soap-client windows-8

如果有可能将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();
Run Code Online (Sandbox Code Playgroud)

更新:

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>
Run Code Online (Sandbox Code Playgroud)

信封中的标题属性应为空

小智 32

试着用这个:

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();
}
Run Code Online (Sandbox Code Playgroud)

请参阅此处了解更多详情.

  • 这应该标记为答案,对我有用。谢谢 (2认同)
  • 如果当前客户端中不存在InnerChanner(我正在尝试使用SOAP调用) (2认同)

Xyr*_*oid 3

尝试这个

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();
}
Run Code Online (Sandbox Code Playgroud)