C # dynamically call WebService and process different returned results

Source: Internet
Author: User

In Asp.net, the normal way to call WebService is to add web references, but it is not very suitable in some special cases. If the WebService address changes frequently, rereference and compile each time.ProgramIt is a very troublesome thing. Here, you only need to configure an address to dynamically reference ws.

I found manyArticleThe specific implementation is similar, basically the same paragraphCode.

Refer to the articles on both sides:

This is an introduction to dynamic calls, mainly using the code of this Buddy:

Http://hddev.blog.51cto.com/3365350/628288

This section describes how to use reflection to obtain the returned array. Although there is an error in the returned array, it is still in the general direction:

Http://blog.csdn.net/study_live/article/details/5225073

The main WebService proxy code can be downloaded at the bottom of the first article.

Webserviceproxy

 Using  System;  Using  System. Web. Services. description; Using  System. IO;  Using  System. net;  Using  System. xml. serialization;  Using  System. codedom;  Using  System. codedom. compiler;  Using  System. reflection;  Public   Class  Webserviceproxy {  Private  String _ Classname = Null  ;  Public   String  Webserviceurl {  Get  ;  Private   Set  ;}  Private Webserviceproxy ( String  Webserviceurl ){  This . Webserviceurl = webserviceurl + "  ? WSDL  "  ; _ Classname = Webserviceurl. substring (webserviceurl. lastindexof ( '  /  ' ) + 1  ); _ Classname = _ Classname. substring ( 0 , _ Classname. lastindexof ( '  .  '  ));} ///   <Summary>      ///  Generate an instance based on the Compilation result and return  ///   </Summary>      ///   <Returns> </returns>      Public   Static   Object Createinstance ( String  Webserviceurl) {webserviceproxy proxy = New Webserviceproxy (webserviceurl); codecompileunit = Proxy. getservicecompileunit (proxy. webserviceurl); compilerresults result = Proxy. Compile (unit); Assembly ASM = Result. compiledassembly;  Object OBJ = ASM. createinstance ( "  WebService.  " + Proxy. _ classname );  Return  OBJ ;} ///   <Summary>      ///  Obtain compileunit  ///   </Summary>      ///   <Param name = "webserviceurl"> </param>      ///   <Returns> </returns>      Private Codecompileunit getservicecompileunit ( String  Webserviceurl) {WebClient Client = New WebClient (); stream = Client. openread (webserviceurl );  //  The URL points to an XML file that contains all the information about the service.  //  Then, the source code to be compiled can be generated by parsing the XML file. If you are interested, take a look at the XML content. Servicedescription description = Servicedescription. Read (Stream); servicedescriptionimporter importer = New Servicedescriptionimporter (); //  Create a client proxy Importer. protocolname = " Soap  " ; //  Specify the access protocol. Importer. Style = servicedescriptionimportstyle. client; //  Generate a client proxy. Importer. codegenerationoptions = codegenerationoptions. generateproperties | Codegenerationoptions. generatenewasync; importer. addservicedescription (description,  "" , "" ); //  Add a WSDL document. Codenamespace nmspace =New Codenamespace (); //  Namespace Nmspace. Name = "  WebService  "  ; Codecompileunit Unit = New  Codecompileunit (); Unit. namespaces. Add (nmspace); servicedescriptionimportwarnings warning = Importer. Import (nmspace, Unit );  Return  Unit ;}  ///  <Summary>      ///  Compile  ///   </Summary>      ///   <Param name = "unit"> </param>      ///   <Returns> </returns>      Private  Compilerresults compile (codecompileunit) {codedomprovider = Codedomprovider. createprovider ( "  CSHARP  " ); Compilerparameters = New  Compilerparameters (); compilerparameters. generateexecutable = False  ; Compilerparameters. generateinmemory = True  ;  //  CP. outputassembly = "D: \ test. dll"; you can also output the variant result to the DLL file to view the compiled result. If you are interested, take a look. Compilerparameters. referencedassemblies. Add ( "  System. dll "  ); Compilerparameters. referencedassemblies. Add (  "  System. xml. dll  "  ); Compilerparameters. referencedassemblies. Add (  "  System. Web. Services. dll  "  ); Compilerparameters. referencedassemblies. Add (  "  System. Data. dll  "  ); Compilerresults =Codedomprovider. compileassemblyfromdom (compilerparameters, Unit );  If  (Compilerresults. errors. haserrors ){  String Errors = ""  ;  Foreach ( VaR Item In  Compilerresults. Errors) {errors + = Item. tostring () + Environment. newline ;}  Throw  New Exception ( "  Compile error:  " + Errors );}  Return  Compilerresults ;}} 
Webserviceclient. CS

 Using  System;  Using  System. reflection;  ///   <Summary>  /// Summary Description for webserviceclient  ///   </Summary>  Public   Class  Webserviceclient {  Public   Static   String Invoke ( String Webserviceurl, String Methodname, Object  [] Parameters ){  If (String  . Isnullorempty (webserviceurl )){  Throw   New Exception ( "  WebService URL required!  "  );}  If ( String  . Isnullorempty (methodname )){  Throw   New Exception ( " Method Name required!  "  );}  Object Instance = Webserviceproxy. createinstance (webserviceurl); methodinfo Method = Instance. GetType (). getmethod (methodname );  String Result = ( String  ) Method. Invoke (instance, parameters );  Return  Result ;}} 

 

Test method: return the string, able, and generic sets respectively (here is actually an array of object classes)

String Url = "Here is your WebService address.  " ; //  It can be stored in the configuration file.          ///  /Return string          //  String S = webserviceclient. Invoke (URL, "getservername", null );  //  Response. Write (s );          Object Instance = Webserviceproxy. createinstance (URL );  /// /Return datatable          //  Methodinfo method = instance. GetType (). getmethod ("getsubstationinfo ");  //  Method Name  //  Object [] parameters = {"370102002 "};  //  Parameters  //  Datatable dt = (datatable) method. Invoke (instance, parameters );  //  Returns a generic set. Methodinfo method = instance. GetType (). getmethod ("  Getrealdata  " ); //  Method Name  //  If the parameter is a dataset, dataset DS = new dataset (); object [] parameters = {DS };          Object [] Parameters = { "  1510  " , "  5  " }; // Parameters  //  Here, an array of object classes is returned.          Object Objarray = Method. Invoke (instance, parameters); Type TP = Objarray. GetType ();  If  (Tp. isarray ){  Object [] Dataarray = objarray As   Object  [];  For ( Int I = 0 ; I <dataarray. length; I ++ ){  Object S = dataarray [I] As   Object  ; Type T = S. GetType ();  //  Use the following method to obtain the attribute values in the object class.  //  Propertyinfo [] Fi = T. getproperties ();  // String STR = Fi [0]. getvalue (S, null). tostring ();                                  String C0001_item_code = T. getproperty ( "  C0001_item_code  " ). Getvalue (S, Null  ). Tostring ();  String C0007_pname = T. getproperty ( "  C0007_pname  " ). Getvalue (S, Null  ). Tostring (); //  Fieldinfo [] fields = T. getfields ();  //  Returns all public fields of the current type.  }} 

 

 

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.