如何在WCF中获取自定义SOAP头的值

6

我创建了一个自定义的SOAP头,并通过IClientMessageInspector将其添加到我的消息中

    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
    {
        var header = new MessageHeader<AuthHeader>();
        header.Content = new AuthHeader(Key);
        header.Actor = "Anyone";
        var header2 = header.GetUntypedHeader("Auth", "xWow");
        request.Headers.Add(header2);
        return null;
    }

    [DataContract(Name="Auth")]
    public class AuthHeader
    {
        public AuthHeader(string key)
        {
            this.Key = key;
        }

        [DataMember]
        public string Key { get; set; }
    }

我还有一个IDispatchMessageInspector,并且我可以在列表中找到正确的标题。但是,它没有值。我知道这个值已经正确地通过了网络,因为消息字符串是正确的。

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
        <Auth s:actor="Anyone" xmlns="xWow" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
            <Key xmlns="http://schemas.datacontract.org/2004/07/xWow.Lib">HERE IS MY KEY VALUE!!!!</Key>
        </Auth>
        <To s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://localhost:26443/AuthService.svc</To>
        <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IAuthService/GetPayload</Action>
    </s:Header>
    <s:Body>
        <GetPayload xmlns="http://tempuri.org/"/>
    </s:Body>
</s:Envelope>

但似乎没有任何属性可用于检索此值。MessageHeaderInfo类具有Actor等属性,但我找不到其他有用的属性。

在客户端上,我必须在Header和Untyped header之间进行转换,服务器上有等效的操作吗?

我找到了以下内容,应该可以解决问题。

request.Headers.FindHeader("Auth", "xWow");
request.Headers.GetHeader<AuthHeader>(index);

如果我手动找到正确的索引并调用第二行,它可以按预期工作。然而,FindHeader返回-1作为索引,即使我已在监视窗口中确认这些名称和命名空间的值是正确的。

3个回答

6
request.Headers.FindHeader("Auth", "xWow");
request.Headers.GetHeader<AuthHeader>(index);

4
HttpRequestMessageProperty requestProperty = 
    (HttpRequestMessageProperty)OperationContext.Current
        .IncomingMessageProperties[HttpRequestMessageProperty.Name];

string contextToken = requestProperty.Headers["MyCustomHeader"];

1

我认为您需要在FindHeader函数中添加第三个参数,即演员(actor)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接