繁体   English   中英

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

[英]C# - Passing header information to SOAP webservice client

我在 Visual Studio 的 C# 项目中添加了 SOAP webservice 作为服务参考,但要么我做错了,要么似乎没有正确解析。 WSDL 清楚地暴露了一个 header 来传递一个身份验证令牌(我可以从另一种方法获得),而这个 header 在我需要使用的方法中被引用(getDeviceInfo)。 相关 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 文件的问题,还是我看错了,有一种完全不同的方式来设置请求的标头?

谢谢!

我不确定这是不是正确的方法,但最后我通过创建一个专用的可序列化 class 进行身份验证并在请求中添加自定义 header 来管理。

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

随着 class 被

[DataContract]
public class Auth
{

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

这样,XML 请求就可以正确构建和发送。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM