С# Soap WebService SoapHeader не появляется в ответ

У меня есть Soap WebService с некоторыми WebMethods.

Некоторые из этих WebMethods получают входные параметры и отправляют выходное значение, а также отправляют и настраиваемый класс в своем заголовке (или, по крайней мере, это то, что я хочу).

Я читал о заголовке SOAP, и в какой-то момент у меня был метод, работающий с классом костюма как в заголовках запросов, так и в заголовках ответов.

Не уверен, что я сделал, но теперь код не работает.

ПРИМЕЧАНИЕ. Я использую SOAP UI для тестирования.

[SoapHeader("npuHeader", Direction = SoapHeaderDirection.Out)]
    public string obterSiteDocumentacaoUrl(NpuHeader npuHeader, string pedido)
    {
        string url = null;

        if (validaNpuHeader(ref npuHeader))
        {
            url = dataAccess.obterSiteDocumentacaoUrl(pedido);
        }

        npuHeader.correlationNPU = npuHeader.npu;
        npuHeader.npu = CreateNPU("", "");
        npuHeader.systemCode = SistemaOrigem;
        npuHeader.creationTime = DateTime.Now;
        npuHeader.operationDate = DateTime.Now;

        return url;
    }

[Serializable]
public class NpuHeader : SoapHeader
{

    public NpuHeader() { }

    public string npu { get; set; }
    public string correlationNPU { get; set; }
    public string systemCode { get; set; }
    public DateTime creationTime { get; set; }
    public DateTime operationDate { get; set; }
    public List<GeneralResponseSuccess> responseSuccess { get; set; }
}
[Serializable]
public class GeneralResponseSuccess
{
    public string errorCode { get; set; }
    public string message { get; set; }
    public string description { get; set; }

    public GeneralResponseSuccess() { }
    public GeneralResponseSuccess(string errorCode, string message, string description)
    { this.errorCodeField = errorCode; this.messageField = message; this.descriptionField = description; }
    public GeneralResponseSuccess(WebServiceBusinessResult error, string description)
    {
        this.errorCode = error.errorCode;
        this.message = error.message;
        this.description = description;
    }
}

Вот тест:

ЗАПРОС

    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:obterSiteDocumentacaoUrl>
         <tem:npuHeader>
           <tem:npu>12345678901234567890123456789012345678901234567890</tem:npu>
            <tem:systemCode>0253</tem:systemCode>
            <tem:creationTime>2015-06-17T00:00:00</tem:creationTime>
            <tem:operationDate>2015-06-17T00:00:00</tem:operationDate>
         </tem:npuHeader>
         <tem:pedido>11SEB9999</tem:pedido>
      </tem:obterSiteDocumentacaoUrl>
   </soapenv:Body>
</soapenv:Envelope>

ОТКЛИК

   <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Body>
      <obterSiteDocumentacaoUrlResponse xmlns="http://tempuri.org/">
         <obterSiteDocumentacaoUrlResult>www.google.com</obterSiteDocumentacaoUrlResult>
      </obterSiteDocumentacaoUrlResponse>
   </soap:Body>
</soap:Envelope>

Если я проверю вкладку заголовка в пользовательском интерфейсе SOAP, объект NPUHeader отсутствует.

Данные ответа заголовка

X-AspNet-Version : 2.0.50727
Date : Mon, 22 Jun 2015 13:53:18 GMT
Content-Length : 422
#status# : HTTP/1.1 200 OK
Content-Type : text/xml; charset=utf-8
Connection : Close
Server : ASP.NET Development Server/9.0.0.0
Cache-Control : private, max-age=0

person FEST    schedule 22.06.2015    source источник
comment
@rudolf_franek, код изменен :)   -  person FEST    schedule 23.06.2015
comment
Ожидается, что направление будет SoapHeaderDirection.InOut.   -  person rudolf_franek    schedule 23.06.2015
comment
Почему? Я только хочу, чтобы объект NPUHeader выводился в заголовке, потому что я хочу, чтобы он был параметром (из-за того, что клиент собирается использовать это, сейчас я должен принять его как параметр). И SoapHeaderDirection имеет параметры In, Out и InOut. Это должно работать правильно?   -  person FEST    schedule 23.06.2015
comment
Почему тогда вы отправляете npuHeader в заголовке запроса? И почему это входной параметр метода obterSiteDocumentacaoUrl?   -  person rudolf_franek    schedule 23.06.2015
comment
Цель заключалась в том, чтобы клиент дал мне NpuHeader в заголовке, но пока они не могут этого сделать и заставили меня указать его как параметр, но мне нужно отправить npuHeader (он будет изменен по сравнению с тем, что я получил) обратно вместе с результатом. Я мог бы обернуть результат и npuheader в класс, но npuheader будет использоваться другими веб-методами, которые возвращают разные типы. Чтобы избежать приведения с моей стороны клиента, я хотел отправить npuheader в заголовке (я думаю, что это имеет смысл, поскольку npuheader — это объект, связанный с соединением, а не вызываемый метод)   -  person FEST    schedule 23.06.2015
comment
@rudolf_franek спасибо за помощь :)   -  person FEST    schedule 25.06.2015


Ответы (1)


Решение найдено при повторном просмотре документа MSN: https://msdn.microsoft.com/en-US/library/8728chd5(v=vs.80).aspx

Дело в том, что когда мы хотим, чтобы что-то путешествовало как SOAPHeader, нам нужно сделать 3 вещи:

  1. Создайте класс расширения SOAPHeader
  2. Создайте общедоступный атрибут в веб-сервисе класса
  3. Пометьте им веб-метод (

    [SoapHeader([attribute_name], Direction = SoapHeaderDirection.[выбрать])]

Когда я впервые попробовал, у меня было все это, но затем, поскольку я хотел получить объект в качестве параметра и использовать его в заголовке ответа, я удалил общедоступный атрибут, думая, что будет использоваться переданный объект.

Кажется, что это не может работать таким образом, поэтому решение было:

  1. Убедитесь, что у меня есть 3 шага, указанные выше
  2. Убедитесь, что переданный параметр и атрибут не конфликтуют по имени.
  3. (В моем случае) Скопируйте необходимые атрибуты данного параметра в атрибут

Следует коду для моего конкретного случая, но должен помочь всем, кто сталкивается с похожей проблемой:

public NpuHeader npuHeaderOut = new NpuHeader();
...
[SoapHeader("npuHeaderOut", Direction = SoapHeaderDirection.Out)]
public string obterSiteDocumentacaoUrl(NpuHeader npuHeader, string pedido)
{
    string url = null;

    if (validaNpuHeader(ref npuHeader))
    {
        try
        {
            url = dataAccess.obterSiteDocumentacaoUrl(pedido);

            npuHeader.ResponseSuccess.Add(
                    new GeneralResponseSuccess(WebServiceBusinessResult.SUCESSO, "Sucesso")
                    );
        }
        catch (Exception ex)
        {
            npuHeader.ResponseSuccess.Add(
                new GeneralResponseSuccess(WebServiceBusinessResult.OUTROS, ex.Message)
            );
        }
    }

    npuHeaderOut.ResponseSuccess = npuHeader.ResponseSuccess;
    npuHeaderOut.correlationNPU = npuHeader.npu;
    npuHeaderOut.npu = CreateNPU("", "");
    npuHeaderOut.systemCode = SistemaOrigem;
    npuHeaderOut.creationTime = DateTime.Now;
    npuHeaderOut.operationDate = DateTime.Now;

    return url;
}

ЗАПРОС МЫЛА

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:obterSiteDocumentacaoUrl>
         <tem:npuHeader>
            <tem:npu>12345678901234567890123456789012345678901234567890</tem:npu>
            <tem:systemCode>0253</tem:systemCode>
            <tem:creationTime>2015-06-17T00:00:00</tem:creationTime>
            <tem:operationDate>2015-06-17T00:00:00</tem:operationDate>
         </tem:npuHeader>
         <tem:pedido>11SEB9999</tem:pedido>
      </tem:obterSiteDocumentacaoUrl>
   </soapenv:Body>
</soapenv:Envelope>

МЫЛЬНЫЙ ОТВЕТ

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Header>
      <NpuHeader xmlns="http://tempuri.org/">
         <npu>0253201506250954188630000000000000000000</npu>
         <correlationNPU>12345678901234567890123456789012345678901234567890</correlationNPU>
         <systemCode>253</systemCode>
         <creationTime>2015-06-25T09:54:18.8632144+01:00</creationTime>
         <operationDate>2015-06-25T09:54:18.8632144+01:00</operationDate>
         <ResponseSuccess>
            <GeneralResponseSuccess>
               <errorCode>EPVSEB000</errorCode>
               <message>Sucesso</message>
               <description>Sucesso</description>
            </GeneralResponseSuccess>
         </ResponseSuccess>
      </NpuHeader>
   </soap:Header>
   <soap:Body>
      <obterSiteDocumentacaoUrlResponse xmlns="http://tempuri.org/">
         <obterSiteDocumentacaoUrlResult>www.google.com</obterSiteDocumentacaoUrlResult>
      </obterSiteDocumentacaoUrlResponse>
   </soap:Body>

person FEST    schedule 25.06.2015