开发者

Obtaining a value within a SOAP Header from the OperationContext

I have the following code in C# that looks for an apiKey in the the following SOAP header:

SOAP Header:

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

C#:

This is what I have so far:

public string GetAPIKey(OperationContext operationCont开发者_StackOverflowext)
{
    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;
}

PROBLEM: Returning null instead of the actual apiKey value:

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

UPDATE 1:

I added some logging. It looks like h.Name is in fact "Authentication", which means it won't actually be looking for "apiKey", which then means it won't be able to retrieve the value.

Is there a way to grab the <apiKey /> inside of <Authentication />?

UPDATE 2:

Ended up using the following code:

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


I think your h.Name is Authentication because it is root type and apiKey is property of Authentication type. Try logging values of h.Name to some log file and check what does it return.

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


Ended up using the following code:

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


There is a shorter solution:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜