如何处理 XML Web services 客户端所要求的 SOAP 标头

客户端可以要求 Web 服务方法正确截获 SOAP 标头的语义并对其进行相应处理,以使得 SOAP 请求成功。 为此,客户端将 SOAP 标头的 mustUnderstand 属性设置为 1。例如,下面的 SOAP 请求要求 SOAP 请求收件人处理 MyCustomSoapHeader SOAP 标头。

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" >
  <soap:Header>
    <MyCustomSoapHeader soap:mustUnderstand="1" xmlns="http://www.contoso.com">
      <custom>Keith</custom>
    </MyCustomSoapHeader>
  </soap:Header>
  <soap:Body>
    <MyUnknownHeaders xmlns="http://www.contoso.com" />
  </soap:Body>
</soap:Envelope>

Web 服务是否定义 SOAP 标头决定了 Web 服务应如何处理客户端所要求的 SOAP 标头。 当 Web 服务定义 SOAP 标头时,ASP.NET 会处理许多工作。 在下面的过程中,可以了解如何处理两种情况。

处理 Web 服务未定义但 Web 服务客户端要求的 SOAP 标头

  • 执行处理来自 Web 服务客户端的未知 SOAP 标头的步骤,并特别关注该 SOAP 标头的 DidUnderstand 属性。

    对于 Web 服务未定义的 SOAP 标头,DidUnderstand 的初始值为 false。 如果 ASP.NET 在 Web 服务方法返回后检测到 DidUnderstand 属性设置为 false 的 SOAP 标头,则会自动引发 SoapHeaderException

处理 Web 服务客户端要求并且 Web 服务已定义的 SOAP 标头

  • 在每个 Web 服务方法内使用 ASP.NET 创建的 Web 服务内,执行处理 SOAP 标头的步骤。

    对于由 Web 服务定义并在接收该 SOAP 标头的 Web 服务方法中处理的 SOAP 标头,ASP.NET 假定 Web 服务了解 SOAP 标头并将 DidUnderstand 的初始值设置为 true

示例

下面的 MyWebService Web 服务定义 MyHeader SOAP 标头并要求将它与对 MyWebMethod Web 服务方法的任何调用一起发送。 此外,MyWebMethod 还处理任何未知的 SOAP 标头。 对于 MyWebMethod 可以处理的 SOAP 标头,DidUnderstand 设置为 true

using System.Web.Services;
using System.Web.Services.Protocols;

// Define a SOAP header by deriving from the SoapHeader base class.
public class MyHeader : SoapHeader {
    public string MyValue;
}
public class MyWebService {
    public MyHeader myHeader;

    // Receive all SOAP headers other than the MyHeader SOAP header.
    public SoapUnknownHeader[] unknownHeaders;
 
    [WebMethod]
    [SoapHeader("myHeader")]
    //Receive any SOAP headers other than MyHeader.
    [SoapHeader("unknownHeaders")]
    public string MyWebMethod() 
    {
       foreach (SoapUnknownHeader header in unknownHeaders) 
       {
         // Perform some processing on the header.
         if (header.Element.Name == "MyKnownHeader")
               header.DidUnderstand = true;
         else
                // For those headers that cannot be 
                // processed, set DidUnderstand to false.
                header.DidUnderstand = false;
       }
       return "Hello";
    }
}
Note注意:

ASP.NET 使用 DidUnderstand 属性来与 Web 服务方法进行通信。 它不属于 SOAP 规范;它的值不会出现在 SOAP 请求或 SOAP 响应的任何部分中。

Note注意:

如果 Web 服务转发 SOAP 标头,则遵循 SOAP 规范中的规则非常重要,尤其是与 Actor 的值有关的规则。 有关详细信息,请参见 W3C 网站 (http://www.w3.org/TR/SOAP/)。

  

原文地址:https://www.cnblogs.com/yangzhx/p/3602042.html