添加SOAP标头以请求

问题描述 投票:3回答:1

我一直在尝试向SOAP请求添加标头,如下所示

<soapenv:Header>
     <UsernameToken xmlns="http://test.com/webservices">username</UsernameToken>
     <PasswordText xmlns="http://test.com/webservices">password</PasswordText>
     <SessionType xmlns="http://test.com/webservices">None</SessionType>
</soapenv:Header>

我找到了使用SoapHeader来包含标题值的建议,但是引入了另一个级别,例如

<soapenv:Header>
    <CustomHeader>
        <UsernameToken xmlns="http://test.com/webservices">username</UsernameToken>
        <PasswordText xmlns="http://test.com/webservices">password</PasswordText>
        <SessionType xmlns="http://test.com/webservices">None</SessionType>
    </CustomHeader>
</soapenv:Header>

任何人都可以建议我如何在没有CustomHeader的情况下形成请求。

c# wcf soap soap-client soapheader
1个回答
4
投票

尝试使用这个

private static void Main()
{
    using (var client = new ServiceClient())
    using (var scope = new OperationContextScope(client.InnerChannel))
    {
        MessageHeader usernameTokenHeader = MessageHeader.CreateHeader("UsernameToken",
            "http://test.com/webservices", "username");
        OperationContext.Current.OutgoingMessageHeaders.Add(usernameTokenHeader);

        MessageHeader passwordTextHeader = MessageHeader.CreateHeader("PasswordText",
            "http://test.com/webservices", "password");
        OperationContext.Current.OutgoingMessageHeaders.Add(passwordTextHeader);

        MessageHeader sessionTypeHeader = MessageHeader.CreateHeader("SessionType",
            "http://test.com/webservices", "None");
        OperationContext.Current.OutgoingMessageHeaders.Add(sessionTypeHeader);

        string result = client.GetData(1);
        Console.WriteLine(result);
    }
    Console.ReadKey();
}

Service Trace查看器显示以下内容

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
        <UsernameToken xmlns="http://test.com/webservices">username</UsernameToken>
        <PasswordText xmlns="http://test.com/webservices">password</PasswordText>
        <SessionType xmlns="http://test.com/webservices">None</SessionType>
        <To s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://localhost:13332/Service1.svc</To>
        <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IService/GetData</Action>
    </s:Header>
</s:Envelope>

看看OperationContextScope了解更多信息

© www.soinside.com 2019 - 2024. All rights reserved.