C# 如何将 HTTP 标头添加到 SOAP 客户端
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18886660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add HTTP Header to SOAP Client
提问by kappie
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.
如果可以向soap客户端Web服务调用添加HTTP标头,有人可以回答我吗?在网上冲浪后,我发现唯一的问题是如何添加 SOAP 标头。
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
信封中的标题属性应为空
回答by Xyroid
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();
}
回答by Qué Padre
var client = new MyServiceSoapClient();
using (new OperationContextScope(InnerChannel))
{
WebOperationContext.Current.OutgoingRequest.Headers.Add("myCustomHeader", "myValue");
}
回答by Ivan Melnikov
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 herefor more detail.
有关更多详细信息,请参见此处。