如何在AfterReceiveRequest()方法中读取自定义标头

时间:2013-10-31 16:00:24

标签: c# .net wcf

我正在使用AfterReceiveRequest()方法,如下所示

public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{

}

我正在获取整个邮件标题,如下所示( request.ToString() ):

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">

<s:Header>

<MyHeader xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <AppIp xmlns="http://schemas.datacontract.org/2004/07/WcfTest">192.168.1.0</AppIp>
  <AppPwd xmlns="http://schemas.datacontract.org/2004/07/WcfTest">UITPass</AppPwd>
  <Appid xmlns="http://schemas.datacontract.org/2004/07/WcfTest">UIT</Appid>
  <ShibbolethSessionID i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/WcfTest" />
  <UCLALogonID i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/WcfTest" />
  <UserUID i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/WcfTest" />
</MyHeader>

<To s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://localhost:60729/Service/StudyListService.svc</To>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IStudyListService/GetStudyListData</Action>

</s:Header>

</s:Envelope>

我想使用request.Headers读取 节点。 MyHeader

默认情况下,request.Headers为操作节点提供属性,如下所示:

request.Headers.To
request.Headers.Action

类似有没有办法获得 request.Headers.MyHeader

感谢任何想法。

2 个答案:

答案 0 :(得分:1)

public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
    var header = request.Headers.GetHeader<MyHeader>("MyHeader", "replace this with you custom namespace uri");

    var userId = header.UserUID;

    // ...
    // ...
    // ...

    return null; 
}

答案 1 :(得分:0)

我通过解析整个XML来解决它:

var requestXML = request.ToString();
var headerData = System.Text.Encoding.UTF8.GetBytes(requestXML);
  using (MemoryStream memoryStream = new MemoryStream(headerData))
  {
         using (XmlReader xmlReader = new XmlTextReader(memoryStream))
         {
              xmlReader.MoveToContent();
              while (xmlReader.Read())
              {
                  if (xmlReader.NodeType == XmlNodeType.Element)
                  { 
                      //read whatever element is desired      
                  }
               }
          }
    }