C#-将标头信息传递给SOAP Web服务客户端

时间:2020-07-09 16:21:19

标签: c# web-services soap wsdl

我已经在Visual Studio的C#项目中添加了SOAP Web服务作为服务引用,但是我做错了或者似乎没有正确解析。 WSDL清楚地公开了用于传递身份验证令牌的标头(我可以从其他方法获取),并且该标头在我需要使用的方法(getDeviceInfoRequest)中被引用。以下相关的WSDL位:

<wsdl:message name="getDeviceInfoRequest">
<wsdl:part name="Auth" type="types:Auth"/>
<wsdl:part name="DeviceName" type="xsd:string"/>
</wsdl:message>

<wsdl:operation name="getDeviceInfo">
<wsdl:input name="getDeviceInfoRequest" message="tns:getDeviceInfoRequest"/>
<wsdl:output name="getDeviceInfoResponse" message="tns:getDeviceInfoResponse"/>
</wsdl:operation>

<wsdl:operation name="getDeviceInfo">
<soap:operation soapAction="" style="rpc"/>
<wsdl:input name="getDeviceInfoRequest">
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:NetworkService" use="encoded" parts="DeviceName"/>
<soap:header encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:NetworkService" use="encoded" message="tns:getDeviceInfoRequest" part="Auth"/>
</wsdl:input>
<wsdl:output name="getDeviceInfoResponse">
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:NetworkService" use="encoded"/>
</wsdl:output>
</wsdl:operation>

<xsd:complexType name="Auth">
<xsd:sequence>
<xsd:element name="token" nillable="false" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>

但是,当我在Visual Studio中生成客户端代理(参考->添加服务参考)时,无法将令牌传递给getDeviceInfoRequest方法,因为它是使用单个参数(DeviceName)生成的。这是WSDL文件解析的问题吗?还是我看错了方法,而在请求上设置标头的方式却完全不同?

谢谢!

1 个答案:

答案 0 :(得分:1)

我不确定这是否是正确的方法,但最后我通过创建专用的可序列化类进行身份验证并向请求添加自定义标头来进行管理。

        LanDB.NetworkServiceInterfaceClient client = new LanDB.NetworkServiceInterfaceClient();
        String token = client.getAuthToken("user", "name", "domain");
        Auth tokenAuth = new Auth(token);
        LanDB.DeviceInfo selectedPLCInfo = new LanDB.DeviceInfo();

        // Add a SOAP autentication Header (Header property in the envelope) to the outgoing request.
        using (new OperationContextScope(client.InnerChannel))
        {
            MessageHeader aMessageHeader = MessageHeader.CreateHeader("Auth", "", tokenAuth);
            OperationContext.Current.OutgoingMessageHeaders.Add(aMessageHeader);
            selectedPLCInfo = client.getDeviceInfo("plcHostname");
        }

正在上课

[DataContract]
public class Auth
{

    [DataMember]
    string token;
    public Auth(string value)
    {
        token = value;
    }
}

通过这种方式正确构建和发送XML请求。

此外,如果我将服务添加为Web服务而不是服务引用,则不需要这些。在那种情况下,我在客户端中得到一个对象,可以使用正确的令牌设置(AuthValue),并且客户端代码可以处理所有内容。走吧!

相关问题