C # calls the WebService service (dynamic invocation)

Source: Internet
Author: User
Tags wsdl

Original: C # invoke WebService service (dynamic invocation)

1 Creating WebService

Using system;using system.web.services;namespace webservice1{//<summary>///    Service1 Summary description//    </summary>    [WebService (Namespace = "http://tempuri.org/", description= "Test Service")]    [WebServiceBinding ( ConformsTo = wsiprofiles.basicprofile1_1)]    [System.ComponentModel.ToolboxItem (false)]    //To allow the use of ASP. AJAX calls this Web service from the script, uncomment the downstream.    [System.Web.Script.Services.ScriptService] public    class Service1:System.Web.Services.WebService    {        [WebMethod (description= "Hello World")] public        string HelloWorld ()        {            return ' Hello world ';        }        [WebMethod (description= "a plus B")] public        int Add (int a, int b)        {            return a + b;        }        [WebMethod (description= "Acquisition Time")]        public string GetDate ()        {            return DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss");        }    }

After the service is created, enter the service address in the browser as shown in.



2 Adding service references through Visual Studio

Adding a service reference through Visual Studio is quite handy, just by choosing to add a service reference in Visual Studio, you can generate a proxy class that invokes the service through the proxy in your project, as shown in.




After you add a service reference, there is more service references and App. Config in the project solution, as shown in.



ServiceReference1 is the service added above, app. Config is the configuration file for the service, and the configuration in App. Config is as follows, when the service address changes, modify the address in the endpoint.

<!--app. Config file configuration--><?xml version= "1.0" encoding= "Utf-8"?><configuration> <configsections                 > </configSections> <system.serviceModel> <bindings> <basicHttpBinding> <binding name= "Service1Soap" closetimeout= "00:01:00" opentimeout= "00:01:00" Receivet imeout= "00:10:00" sendtimeout= "00:01:00" allowcookies= "false" Bypassproxyonlocal= "false" Hostnamecompar Isonmode= "StrongWildcard" maxbuffersize= "65536" maxbufferpoolsize= "524288" maxreceivedmessagesize= "6553 6 "messageencoding=" Text "textencoding=" Utf-8 "transfermode=" Buffered "Usedefaultweb                        Proxy= "true" > <readerquotas maxdepth= "maxstringcontentlength=" 8192 "maxarraylength=" 16384 " Maxbytesperread= "4096" maxnametablecharcount= "16384"/> <security mode= "None "> &LT;transport clientcredentialtype= "None" proxycredentialtype= "None" realm= ""/>                <message clientcredentialtype= "UserName" algorithmsuite= "Default"/> </security>            </binding> </basicHttpBinding> </bindings> <client> <endpoint address= "Http://localhost:19951/Service1.asmx" binding= "BasicHttpBinding" Bindingconfigur ation= "Service1Soap" contract= "Servicereference1.service1soap" name= "Service1Soap"/> </client > </system.serviceModel></configuration>

Client calls WebService

Invokes the service, the result. static void Main (string[] args) {    servicereference1.service1soapclient client = new Servicereference1.service1soapclient ();    Call the HelloWorld method of the service    string hello = client. HelloWorld ();    Console.WriteLine ("Call service HelloWorld method, return {0}", hello);    Call the service's Add method    int a = 1, b = 2;    int add = client. Add (A, b);    Console.WriteLine ("Invoke service Add method, {0} + {1} = {2}", A, B, add);    The GetDate method that invokes the service    string date = client. GetDate ();    Console.WriteLine ("Call service GetDate method, return {0}", date);    Console.readkey ();}



3 dynamic Invoke service (go from http://www.cnblogs.com/prolifes/articles/1235685.html)

Using system;using system.codedom;using system.codedom.compiler;using system.io;using System.Net;using system.reflection;using system.web.services.description;using microsoft.csharp;static void Main (string[] args) {//    Service address, which can be placed in the program's configuration file, so that even if the service address changes, there is no need to recompile the program.    String url = "Http://localhost:19951/Service1.asmx";    The client proxy service namespace, which can be set to the desired value. string ns = String.    Format ("Proxyservicereference");    Gets the wsdl WebClient WC = new WebClient (); Stream stream = WC. OpenRead (URL + "?)    WSDL "); ServiceDescription sd = Servicedescription.read (stream);//Service description information can be obtained by servicedescription string classname = sd. Services[0].    Name;    ServiceDescriptionImporter SDI = new ServiceDescriptionImporter (); Sdi.    Addservicedescription (SD, "", "");    CodeNamespace cn = new CodeNamespace (NS);    Generate the client proxy class code CodeCompileUnit CCU = new CodeCompileUnit (); Ccu.    Namespaces.add (CN); Sdi.    Import (CN, CCU);    CSharpCodeProvider csc = new CSharpCodeProvider (); Set compilation parameters CompilerParameters Cplist = new CompilerParameters (); 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");    Compiler proxy class CompilerResults CR = Csc.compileassemblyfromdom (cplist, CCU); if (CR.        Errors.haserrors = = True) {System.Text.StringBuilder sb = new System.Text.StringBuilder (); foreach (System.CodeDom.Compiler.CompilerError ce in CR. Errors) {sb. Append (CE.            ToString ()); Sb.        Append (System.Environment.NewLine); } throw new Exception (sb.)    ToString ());    }//Generate proxy instance and call method Assembly Assembly = cr.compiledassembly; Type t = assembly.    GetType (ns + "." + ClassName, True, true);    Object obj = activator.createinstance (t); ////////////////////////////////////////////////////////////////////////////////////    //Call the HelloWorld method MethodInfo HelloWorld = T.getmethod ("HelloWorld");    Object Helloworldreturn = Helloworld.invoke (obj, null);    Console.WriteLine ("Call HelloWorld method, return {0}", helloworldreturn.tostring ());    Gets the parameter of the Add method parameterinfo[] Helloworldparaminfos = Helloworld.getparameters ();    Console.WriteLine ("HelloWorld method has {0} parameters:", helloworldparaminfos.length); foreach (ParameterInfo paraminfo in Helloworldparaminfos) {Console.WriteLine ("parameter name: {0}, Parameter type: {1}", Paraminfo.name    , paramInfo.ParameterType.Name);    }//Gets the data type returned by HelloWorld string helloworldreturntype = HelloWorld.ReturnType.Name; Console.WriteLine ("The data type returned by HelloWorld is {0}", Helloworldreturntype);////////////////////////////////////////////// Console.WriteLine ("\n===================================================        ===========");    Call the Add method MethodInfo add = T.getmethod ("add");    int a = ten, b = parameter of the 20;//add method object[] Addparams = new object[]{a, b}; ObjectAddreturn = Add.    Invoke (obj, addparams);    Console.WriteLine ("Call the HelloWorld method, {0} + {1} = {2}", A, B, addreturn.tostring ()); Gets the parameter of the Add method parameterinfo[] Addparaminfos = Add.    GetParameters ();    Console.WriteLine ("Add method has {0} parameters:", addparaminfos.length); foreach (ParameterInfo paraminfo in Addparaminfos) {Console.WriteLine ("parameter name: {0}, argument type: {1}", Paraminfo.name, param    Info.ParameterType.Name); }//Gets the data type returned by the Add string Addreturntype = Add.    Returntype.name; Console.WriteLine ("Add returned data type: {0}", Addreturntype);////////////////////////////////////////////////////////////        Console.WriteLine ("\n==============================================================");    Call the GetDate method MethodInfo getDate = T.getmethod ("GetDate");    Object Getdatereturn = Getdate.invoke (obj, null);    Console.WriteLine ("Call getdate method, return {0}", getdatereturn.tostring ());    Gets the parameter of the GetDate method parameterinfo[] Getdateparaminfos = Getdate.getparameters (); Console.writeliNE ("getdate method has {0} parameters:", getdateparaminfos.length); foreach (ParameterInfo paraminfo in Getdateparaminfos) {Console.WriteLine ("parameter name: {0}, Parameter type: {1}", Paraminfo.name, p    AramInfo.ParameterType.Name);    }//Gets the data type returned by the Add string getdatereturntype = GetDate.ReturnType.Name;    Console.WriteLine ("GetDate returned data type: {0}", Getdatereturntype);    Console.WriteLine ("\n\n==============================================================");    Console.WriteLine ("Service Information"); Console.WriteLine ("Service name: {0}, Service description: {1}", SD. Services[0]. Name, SD. Services[0].    documentation); Console.WriteLine ("Service provided {0} methods:"), SD. Porttypes[0].    Operations.count); foreach (Operation op in SD. Porttypes[0]. Operations) {Console.WriteLine ("method name: {0}, Method Description: {1}", Op. Name, Op.    documentation); } console.readkey ();}


C # calls the WebService service (dynamic invocation)

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.