簡體   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