2011-08-31 19 views
0

我需要將自定義標題放入WCF。我的代碼如下:WCF設置自定義標題 - 閱讀不工作

ServiceReference1.Service2Client ws = new Service2Client(); 
    using (OperationContextScope scope = new OperationContextScope((IContextChannel)ws.InnerChannel)) 
     { 
      MessageHeaders messageHeadersElement = OperationContext.Current.OutgoingMessageHeaders; 
      messageHeadersElement.Add(MessageHeader.CreateHeader("Authorization", String.Empty, "string")); 
      messageHeadersElement.Add(MessageHeader.CreateHeader("username", String.Empty, "user")); 
      var res = ws.GetUser("123"); 
     } 

但是當我嘗試在服務讀它,沒有什麼是在以下

public class OAuthAuthorizationManager : ServiceAuthorizationManager 
    { 
     protected override bool CheckAccessCore(OperationContext operationContext) 
     { 
      int index = OperationContext.Current.IncomingMessageHeaders.FindHeader("username", String.Empty); 

      string auth = operationContext.IncomingMessageHeaders.GetHeader<string>("username", String.Empty); 

      var hereIseeIt = operationContext.RequestContext.RequestMessage; 

指數速效爲-1:找不到

AUTH:也顯示頭部不可用的例外

hereIseeIt:.T​​oString()顯示一個xml,我可以看到該用戶是存在的,但我看不到在一個xml中訪問該信息的方法對象 enter image description here

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> 
    <s:Header> 
    <username xmlns="http://Microsoft.WCF.Documentation">user</username> 
    </s:Header> 
    <s:Body> 
    <GetUser xmlns="http://tempuri.org/"> 
     <UserId>123</UserId> 
    </GetUser> 
    </s:Body> 
</s:Envelope> 

但因爲我發現沒有辦法訪問S我無法訪問他們的紐約:頁眉...

+0

嘗試使用一些自定義XML命名空間,而不是'String.Empty'爲'Add'和'FindHeader' –

+0

你的第二個參數改變 「的String.Empty」 到「HTTP://Microsoft.WCF.Documentation 「到達的XML,但我仍然可以不訪問標題 –

回答

0

嘗試使用:

XPathNavigator XPN = operationContext.RequestContext.RequestMessage.CreateBufferedCopy().CreateNavigator(); 

不優雅,但它給你通過XPathNavigator可以訪問整個消息,這應該可以很容易地得到你想要的消息內的任何值..

一些鏈接:

+0

THX。至少有一種方式來訪問數據... –

0

這裏有一個簡單的方法來獲得username頭的內XML爲您的方案。即使你很早以前就已經解決了你的問題,但我認爲這可能會幫助其他面臨同樣問題的人。

var username = String.Empty; 

// using the namespace from you XML sample 
var usernameHeaderPosition = OperationContext.Current 
    .IncomingMessageHeaders 
    .FindHeader("username", "http://Microsoft.WCF.Documentation"); 

if (usernameHeaderPosition > -1) 
{ 
    username = OperationContext.Current 
     .IncomingMessageHeaders 
     .GetReaderAtHeader(usernameHeaderPosition).ReadInnerXml(); 
}