Как добавить HTTP-заголовок в SOAP-клиент

Может кто-нибудь ответить мне, можно ли добавить HTTP-заголовок к вызовам веб-сервиса мыльного клиента. После серфинга в интернете я обнаружил только то, как добавить заголовок 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>

Свойство заголовка в конверте должно быть пустым

5 ответов

Попробуйте использовать это:

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

Смотрите здесь для более подробной информации.

Попробуй это

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

Чтобы добавить заголовок HTTP к стандартному сгенерированному клиенту SOAP (через ссылку на службу или путем создания клиента с помощью svcutil), вы можете использовать точку расширения Endpoint.Behaviors, которую я нашел наиболее удобной.

Необходимо выполнить пару шагов. Сначала нам нужно создать инспектор сообщений с актуальной функцией, которая будет добавлять HTTP-заголовок ("HEADER_WHICH_WE_WANT") к каждому SOAP-запросу.

      using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;

class MessageInspector : IClientMessageInspector
{
  public object BeforeSendRequest(ref Message request, IClientChannel channel)
  {
    var property = request.Properties.ContainsKey(HttpRequestMessageProperty.Name)?
    request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty: new HttpRequestMessageProperty();

    if (null == property)
      return null;

    property.Headers["HEADER_WHICH_WE_WANT"] = "Actual Value we want";
    request.Properties[HttpRequestMessageProperty.Name] = property;
    return null;
}}

далее нам нужно добавить этот MessageInspector в реализацию интерфейса IEndpointBehavior в точке clientRuntime.MessageInspectors

      using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

internal class InspectorBehavior : IEndpointBehavior
{
  public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
  {
   clientRuntime.MessageInspectors.Add(new MessageInspector());
  }
}

и последнее, что нужно сделать, это зарегистрировать это поведение для клиента SOAP.

      SoapClient.Endpoint.Behaviors.Add(new InspectorBehavior());

вот и все, теперь каждый вызов SOAP будет оснащен пользовательским HTTP-заголовком «HEADER_WHICH_WE_WANT» со значением «фактическое значение, которое мы хотим», которое мы указали в нашем коде.

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

Некоторые из этих ответов добавят заголовки к содержимому XML-текста запроса. Чтобы добавить заголовки к самому запросу, выполните следующие действия:

      SoapServiceClient client = new SoapServiceClient();

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

    var result = client.MyClientMethod();
}

Обратите внимание на изменение OperationContext для WebOperationContext. Вспомогательный класс, обеспечивающий легкий доступ к контекстным свойствам веб-запросов и ответов.

Другие вопросы по тегам