我在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();
}
答案 0 :(得分:7)
我认为您的h.Name
是Authentication
,因为它是根类型,而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;
}