向请求添加SOAP报头

本文关键字:报头 SOAP 添加 请求 | 更新日期: 2023-09-27 18:05:04

我一直在尝试为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的情况下形成请求?

向请求添加SOAP报头

尝试使用这个

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

服务跟踪查看器显示如下

<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获取更多信息