In general, WinForm call WebService when you add a service reference---advanced----add a Web reference------fill out url--add a Web reference to complete a reference to WebService let the vs.net environment generate a service proxy for us, and then call the corresponding Web service. If you need to call WebService dynamically, implement such a function: Publicstaticobjectinvokewebservice (StringUrl, stringmethodname,object[] args), where The URL is the address of the Web service, MethodName is the name of the service method to invoke, and args is the parameter required to invoke the Web service, and the return value is the result of the Web service's return. To implement such a feature, you need skills in these areas: reflection, CodeDom, programming using the C # compiler, WebService. With this knowledge, it is easy to implement dynamic invocation of Web services:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.IO;usingSystem.Net;usingsystem.codedom;usingSystem.CodeDom.Compiler;usingSystem.Web.Services.Description;usingMicrosoft.csharp;namespacenetbanktmp{ Public Static classWebservicehelper {/// <summary> ///Dynamic Call WebService/// </summary> /// <param name= "url" >WebService Address</param> /// <param name= "methodname" >Method Name (module name)</param> /// <param name= "args" >parameter list, no parameter is null</param> /// <returns>Object</returns> Public Static ObjectInvokewebservice (stringUrlstringMethodNameObject[] args) { returnInvokewebservice (URL,NULL, MethodName, args); } /// <summary> ///Dynamic Call WebService/// </summary> /// <param name= "url" >WebService Address</param> /// <param name= "classname" >class name</param> /// <param name= "methodname" >Method Name (module name)</param> /// <param name= "args" >parameter list</param> /// <returns>Object</returns> Public Static ObjectInvokewebservice (stringUrlstringClassNamestringMethodNameObject[] args) { string@namespace ="Fangqm.Netbank.WebService.webservice"; if(ClassName = =NULL|| ClassName = ="") {classname=webservicehelper.getclassname (URL); } //Get Service Description Language (WSDL)WebClient WC =NewWebClient (); Stream Stream= WC. OpenRead (url+"? WSDL");//"1"ServiceDescription sd = Servicedescription.read (stream);//"2"ServiceDescriptionImporter SDI =NewServiceDescriptionImporter ();//"3"Sdi. Addservicedescription (SD,"",""); CodeNamespace cn=NewCodeNamespace (@namespace);//"4"//Generate the client proxy class codeCodeCompileUnit CCU =NewCodeCompileUnit ();//"5"CCU. Namespaces.add (CN); Sdi. Import (CN, CCU); CSharpCodeProvider csc=NewCSharpCodeProvider ();//"6"ICodeCompiler ICC = csc. CreateCompiler ();//"7"//set the compiler's parametersCompilerParameters cplist =NewCompilerParameters ();//"8"Cplist. GenerateExecutable =false; Cplist. GenerateInMemory=true; Cplist. Referencedassemblies.add ("System.dll"); Cplist. Referencedassemblies.add ("System.XML.dll"); Cplist. Referencedassemblies.add ("System.Web.Services.dll"); Cplist. Referencedassemblies.add ("System.Data.dll"); //Compiling proxy classesCompilerResults cr = Icc.compileassemblyfromdom (cplist, CCU);//"9" if(true==Cr. errors.haserrors) {System.Text.StringBuilder sb=NewStringBuilder (); foreach(CompilerError CEinchCr. Errors) {sb. Append (CE. ToString ()); Sb. Append (System.Environment.NewLine); } Throw NewException (sb.) ToString ()); } //build the proxy instance and call the methodSystem.Reflection.Assembly Assembly =cr.compiledassembly; Type T= assembly. GetType (@namespace +"."+ ClassName,true,true); ObjectBJ = Activator.CreateInstance (t);//"10"System.Reflection.MethodInfo mi = t.getmethod (methodname);//"11" returnmi. Invoke (obj, args); } Private Static stringGetClassName (stringURL) { //If the URL is "Http://localhost/InvokeService/Service1.asmx" //The final return value is Service1 string[] parts = URL. Split ('/'); string[] pps = Parts[parts. Length-1]. Split ('.'); returnpps[0]; } }}View Code
The above comment has already explained the function of each code snippet very well, below gives an example to see, this example is to obtain the weather condition of the big city by accessing the Http://www.webservicex.net/globalweather.asmx service.
Stringurl="Http://www.webservicex.net/globalweather.asmx"; string[] args=newstring[2] ; args[0]= This. Textbox_cityname.text; args[1]=" China"; Objectresult=webservicehelper.invokewebservice (URL,"GetWeather", args); This. Label_result.text=result. ToString ();
View Code
If there are no parameters, then the parameter is null The example above, the call Web service uses two parameters, the first is the name of the city, the second is the name of the country, the Web service returns an XML document, The temperature, wind and other weather conditions can be resolved from it. comments about this code "2" The servicedescription class provides a way to create and format a description of the XML Web A valid Web Services Description Language (WSDL) document file for services that is complete and has the appropriate namespaces, elements, and attributes. This class cannot be inherited. The Servicedescription.read method initializes an instance of the ServiceDescription class by loading the XML directly from the Stream instance. the "3" servicedescriptionimporter class exposes a method for generating a client proxy class for XML Web services. The Servicedescriptionimporter.addservicedescription method adds the specified servicedescription to the collection of servicedescriptions values to be imported. "4" CodeNamespace represents a namespace declaration. "5" CodeCompileUnit will provide a CodeDom program circular container, CodeCompileUnit contains a collection, can be stored containing the CodeDom source code prototype, The collection of components referenced by the project and the CodeNamespace object for the collection of Task piece properties. The 6 CSharpCodeProvider class provides an instance of the C # code generator and code compiler. "7" get the C # code compiler's executor "8" Create a compiler parameter instance "9" CompilerResults represents the compiled result returned from the compiler. Compiles a component using the specified compiler settings, based on the system.codedom tree structure contained in the specified array of CodeCompileUnit objects. "10" Activator class packageContains a specific method for creating an object type locally or remotely, or to obtain a reference to an existing remote object. You cannot inherit this class of Activator.CreateInstance method Create an instance of the specified type using the constructor that is the most matched to the specified parameter. An instance of the "11" MethodInfo can be obtained by invoking the GetMethod method of the GetMethods or type object or an object derived from type, or by calling the MethodInfo that represents the generic method definition. MakeGenericMethod method to obtain the.
C # WinForm Dynamic Call WebService Method (GO)