2011-06-21 20 views
9
SOAP頭內而獲得值

我在C#下面的代碼看起來在下面SOAP報頭中的apiKey從的OperationContext

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 

UPDATE 1:

我加了一些記錄。它看起來像h.Name其實是「驗證」,這意味着它實際上不會尋找「apiKey」,這意味着它將無法檢索該值。

有沒有辦法抓住<Authentication />裏面的<apiKey />

更新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

什麼回來呢?您是否調試過應用程序和Web服務? Web服務上是否有相同的數據? –

+1

嘗試在某處登錄h.Name的日誌值 –

+0

我添加了日誌記錄。看到我上面的更新。 – fuzz

回答

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

請嘗試更新的代碼,並讓我知道。 –

+1

你將不得不使用其他的東西,看起來像你的XmlReader是空的,因爲OperationContext.Current.IncomingMessages已經讀取了XmlReader的所有內容,並且它是空的。 MessageHeaderInfo類型中有哪些屬性可用?當你做h時。 ,你在intellisense中看到了什麼,你將不得不使用任何這些屬性來獲得所需的結果。 –

+0

我不得不使用'xr.ReadToDescendant(「apiKey」);'爲了這個工作正常。你帶領我走向正確的方向。謝謝。 – fuzz

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

有一個較短的解決方案:

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; 
} 
相關問題