C# WS Client generálása (Web Reference Solution)
2009. augusztus 13.
Feladat: Web Logic-on futó alkalmazás által kiajánlott WS API-t kellene használnom C# kódból. A nehezítés, hogy az authentikációhoz szükséges infó (username, password, …) a SOAP messagek header-jében van átküldve.
Ezt nem kell nagyon bántanunk. Az alján már látható, amit kerestünk:


6. SOAP Header módosítása C#-ban attributumokkal:
Mivel ugye az authentikációhoz szükséges infó a SOAP messagek headerjében megy át (plain text-en a username és a password
), itt azért még kell egy kicsit trükköznünk. A SOAP message-nek a következőképpen kellene kinéznie:
<soap:envelope soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:header>
<credentials>
<userid>WebService_User</userid>
<password>WebService_User</password>
</credentials>
</soap:header>
<soap:body>
<tns:getuserdetails xsi="http://www.w3.org/2001/XMLSchema-instance"
xsd="http://www.w3.org/2001/XMLSchema"
soapenc="http://schemas.xmlsoap.org/soap/encoding/" tns="atlas">
<string>userId</string>
</tns:getuserdetails>
</soap:body>
</soap:envelope>
Ehhez először is kell egy osztály, ami tartalmazza a userId-t és password-öt és majd bele lesz serializálva a Header-be. Ez az osztály valahogy így néz ki:
public class Credentials : SoapHeader {
private string useridField;
private string passwordField;
public Credentials() { }
public Credentials(string userid, string password) {
this.useridField = userid;
this.passwordField = password;
}
[System.Xml.Serialization.SoapElementAttribute(IsNullable = false)]
public string userid {
get { return this.useridField; }
set { this.useridField = value; }
}
[System.Xml.Serialization.SoapElementAttribute(IsNullable = false)]
public string password {
get { return this.passwordField; }
set { this.passwordField = value; }
}
}
Ezt a Credential class-t példányosítva át kell adnunk a WS Client stub-unknak. A stub osztályban (nálam ez a Reference.cs-ben van) benne vannak a WS methodok, amiket meghívhatunk. Ahhoz, hogy a WS methodok hívásakor legenerálódó SOAP messagek tartalmazzák a Credentials header-t, az első sorban szereplő attributumot be kell szúrnunk a method definíció elé:
[System.Web.Services.Protocols.SoapHeader("Credentials",
Direction = SoapHeaderDirection.InOut)]
[System.Web.Services.Protocols.SoapRpcMethodAttribute("",
RequestNamespace="atlas", ResponseNamespace="atlas")]
[return: System.Xml.Serialization.SoapElementAttribute("result")]
public bool createProduct(AWSProduct aWSProduct) {
object[] results = this.Invoke("createProduct", new object[] {aWSProduct});
return ((bool)(results[0]));
}
Disclaimer: Nem vagyok C# developer. Meg kellett oldanom egy feladatot. Leírtam, hogy ne felejtsem el. Talán más is okul belőle
Kommenteket szívesen fogadok…

2010. március 12. at 12:27
[...] WS Client készítésére C#-ban. A régi “Web Reference” megoldás megtalálható itt. A .NET 3.0-ás verziójában már Service Reference-eket tudunk hozzáadni a project-hez. A [...]