从OperationContext获取SOAP Header中的值

时间:2011-06-21 07:33:14

标签: c# wcf web-services soap

我在C#中有以下代码,用于在以下apiKey标题中查找SOAP

SOAP标头:

<soap:Header>
   <Authentication>
       <apiKey>CCE4FB48-865D-4DCF-A091-6D4511F03B87</apiKey>
   </Authentication>
</soap:Header>

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

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

CCE4FB48-865D-4DCF-A091-6D4511F03B87

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

3 个答案:

答案 0 :(得分:7)

我认为您的h.NameAuthentication,因为它是根类型,而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();
}

答案 1 :(得分:2)

使用以下代码结束:

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

答案 2 :(得分:2)

有一个较短的解决方案:

public string GetAPIKey(OperationContext operationContext)
{
    string apiKey = null;
    MessageHeaders headers = OperationContext.Current.RequestContext.RequestMessage.Headers;

    // Look at headers on incoming message.
    if (headers.FindHeader("apiKey","") > -1)
        apiKey = headers.GetHeader<string>(headers.FindHeader("apiKey",""));        

    // Return the API key (if present, null if not).
    return apiKey;
}