Go C # dynamic Call WebService

Source: Internet
Author: User
Tags wsdl

Usually when we need to call WebService in our program, we use "Add Web Reference" to let the vs.net environment generate a service proxy for us and then call the corresponding Web service. This makes the work simple, but binds to the URL, method name, and parameters that provide the Web service, which is the limit that vs.net automatically generates for us with the Web service proxy. If the URL of the publishing Web service has changed, then we need to re-let Vs.net build the agent and recompile. In some cases, this may be intolerable, and we need the ability to dynamically invoke webservice.      For example, we can save the Web service URL in the configuration file, so that when the service URL changes, only need to modify the configuration file. Having said so much, we are actually going to implement such a function:

Object Invokewebservice (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:

UsingMicrosoft.csharp;UsingSystem;Usingsystem.codedom;UsingSystem.CodeDom.Compiler;UsingSystem.Web.Services.Description;UsingSystem.Xml;NamespacePhy. BOP. mvc4app.app_start{PublicClassWebservicehelper {#region Invokewebservice//Dynamically invoking Web ServicesPublicStaticObject Invokewebservice (String URL,String methodname,Object[] args) {Return Webservicehelper.invokewebservice (URL,Null, methodname, args); }PublicStaticObject Invokewebservice (String URL,String classname,String methodname,Object[] args) {String @namespace ="EnterpriseServerBase.WebService.DynamicWebCalling";if ((classname = =NULL) | | (ClassName = ="") {classname =Webservicehelper.getwsclassname (URL); }Try{//Create and format a WSDL document using the Stream object//WebClient WC = new WebClient ();//Stream stream = WC. OpenRead (URL + "?) WSDL ");//ServiceDescription sd = Servicedescription.read (stream);//Create and format a WSDL document using the XmlTextReader object XmlTextReader reader =New XmlTextReader (URL +"? wsdl"); ServiceDescription SD =Servicedescription.read (reader); ServiceDescriptionImporter SDI =NewServiceDescriptionImporter (); Sdi. Addservicedescription (SD,"",""); CodeNamespace cn =NewCodeNamespace (@namespace);//Generate the client proxy class code CodeCompileUnit CCU =NewCodeCompileUnit (); Ccu. Namespaces.add (CN); Sdi. Import (CN, CCU);//CSharpCodeProvider csc =NewCSharpCodeProvider ();//ICodeCompiler ICC =Csc. CreateCompiler ();//Set compilation parameters CompilerParameters Cplist =NewCompilerParameters (); 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 classes
CSharpCodeProvider csc = new CSharpCodeProvider ();
CompilerResults cr = Csc.compileassemblyfromdom (cplist, CCU);
if (true = =Cr. errors.haserrors) {System.Text.StringBuilder SB =NewSystem.Text.StringBuilder ();foreach (System.CodeDom.Compiler.CompilerError CEInchCr. Errors) {sb. Append (CE. ToString ()); Sb. Append (System.Environment.NewLine); }ThrowNewException (sb.) ToString ()); }//Generates the proxy instance and calls the method System.Reflection.Assembly Assembly =cr.compiledassembly; Type t = assembly. GetType (@namespace +"."+ ClassName,TrueTrue);Object obj =Activator.CreateInstance (t); System.Reflection.MethodInfo mi =T.getmethod (methodname);ReturnMi. Invoke (obj, args); }Catch(Exception ex) {ThrowNew Exception (ex. Innerexception.message,NewException (ex. Innerexception.stacktrace)); } }PrivateStaticString Getwsclassname (StringWsurl) {string[] Parts = Wsurl.split (‘/‘);string[] pps = parts[parts. Length-1]. Split (‘.‘);Return pps[0]; }#endregion//Get the name of the country's corresponding city by webservicePrivateStaticvoid Main (String[] args) {string url = "http:// Www.webservicex.net/globalweather.asmx "; args = new string[1); Args[0] = "china "; object result = Webservicehelper.invokewebservice (URL, getcitiesbycountry "

Reference resources:

Http://www.cnblogs.com/ruochen/archive/2007/12/11/990427.html

http://linglong117.blog.163.com/blog/static/277145472009127514463/

PS: In code

Go C # dynamic Call WebService

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.