从OperationContext获取SOAP Header中的值

fuz*_*uzz 8 c# wcf soap web-services

我有以下代码,在下面的标题C#中查找:apiKeySOAP

SOAP标头:

<soap:Header>
   <Authentication>
       <apiKey>CCE4FB48-865D-4DCF-A091-6D4511F03B87</apiKey>
   </Authentication>
</soap:Header>
Run Code Online (Sandbox Code Playgroud)

C#:

这是我到目前为止:

public string GetAPIKey(OperationContext operationContext)
{
    string apiKey = null;

    // Look at headers on incoming message.
    for (int i = 0; i < OperationContext.Current.IncomingMessageHeaders.Count; i++)
    {
        MessageHeaderInfo h = OperationContext.Current.IncomingMessageHeaders[i];

        // For any reference parameters with the correct name.
        if (h.Name == "apiKey")
        {
            // Read the value of that header.
            XmlReader xr = OperationContext.Current.IncomingMessageHeaders.GetReaderAtHeader(i);
            apiKey = xr.ReadElementContentAsString();
        }
    }

    // Return the API key (if present, null if not).
    return apiKey;
}
Run Code Online (Sandbox Code Playgroud)

问题:返回null而不是实际apiKey值:

CCE4FB48-865D-4DCF-A091-6D4511F03B87
Run Code Online (Sandbox Code Playgroud)

更新1:

我添加了一些日志记录 它看起来h.Name实际上是"身份验证",这意味着它实际上不会寻找"apiKey",这意味着它将无法检索该值.

有没有办法抓住<apiKey />内部<Authentication />

更新2:

使用以下代码结束:

if (h.Name == "Authentication")
{
  // Read the value of that header.
  XmlReader xr = OperationContext.Current.IncomingMessageHeaders.GetReaderAtHeader(i);
  xr.ReadToDescendant("apiKey");
  apiKey = xr.ReadElementContentAsString();
}
Run Code Online (Sandbox Code Playgroud)

Aka*_*ava 7

我认为你h.NameAuthentication因为它是root类型而apiKey是Authentication类型的属性.尝试h.Name将某些日志文件的值记录下来并检查它返回的内容.

if (h.Name == "Authentication")
{
    // Read the value of that header.
    XmlReader xr = OperationContext.Current.IncomingMessageHeaders.GetReaderAtHeader(i);
    //apiKey = xr.ReadElementContentAsString();
    xr.ReadToFollowing("Authentication");
    apiKey = xr.ReadElementContentAsString();
}
Run Code Online (Sandbox Code Playgroud)