我在C#中有以下代码,在以下SOAP头中查找apiKey:
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();
}发布于 2011-06-22 06:44:22
我认为您的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();
}发布于 2011-06-22 11:47:22
最后使用以下代码:
if (h.Name == "Authentication")
{
// Read the value of that header.
XmlReader xr = OperationContext.Current.IncomingMessageHeaders.GetReaderAtHeader(i);
xr.ReadToDescendant("apiKey");
apiKey = xr.ReadElementContentAsString();
}发布于 2014-10-30 08:15:11
有一个较短的解决办法:
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;
}https://stackoverflow.com/questions/6421846
复制相似问题