WebService in C #. NET use

Source: Internet
Author: User
Tags wsdl

Objective

Many recent projects need to call other systems WebService services for processing business, the first real use in the project, feel that some places need attention, so write this article (this article is completely personal use of understanding, understand the wrong place, please correct me)

First, create WebService service

After adding a Web service, VS will automatically generate the WebService service class and include the HelloWorld service method, where the user can customize the service method, such as adding addfunction service methods, marking the method property as [WebMethod]

    /// <summary>    ///Summary description of Dianwebservice/// </summary>[WebService (Namespace ="http://tempuri.org/")] [WebServiceBinding (ConformsTo=Wsiprofiles.basicprofile1_1)] [System.ComponentModel.ToolboxItem (false)]    //to allow the Web service to be called from the script using ASP. NET AJAX, uncomment the downstream. //[System.Web.Script.Services.ScriptService]     Public classDianWebService:System.Web.Services.WebService {[WebMethod]//This property is identified as the WebService service method         Public stringHelloWorld () {return "Hello World"; } [WebMethod] Public intAddFunction (intAintb) {returnA +b; }    }

Second, call the WebService service

Under the. NET platform, there are two ways to invoke the WebService service: one is to add a service reference directly to the project, and the other is to invoke the service through a dynamic proxy.

  

Method One, add the WebService Service reference directly in the project (select "Add Service Reference" from the Project menu)

Description

Address of the regional 1:webservice service

Zone 2: Set the namespace for the WebService service

Zone 3: Further detailed configuration of the introduced service, including access rights to the service, asynchronous, etc.

Description

Zone 1: Define access rights for referenced services, divided into public and internal two types

Zone 2: Determine whether the imported service generates asynchronous operations (not yet available here for what to do)

Zone 3: Configure the Advanced configuration of the Web service, which is configured here, to be accessed directly in the project using the Web service class. Otherwise, the interface methods in the service cannot be accessed directly.

It is important to note that if you do not add a Web reference here, VS will only automatically generate the corresponding Service protocol interface (***SOAP) and Service proxy class (***soapclient) when creating the Web service. In fact, we can view the public interface method in the WebService service through the interface, and invoke the Web service interface method through the service proxy class.

The obvious point is that when you do not add a Web reference, VS automatically creates a service reference (automatically generated under service references), and when you add a reference, VS creates a Web reference (automatically chengcheng under the Web references).

(Here the ***soap and ***soapclient two names are not very standardized, which one danale can guide the two professional terms, how to call them)

Description

Address of the regional 1:webservice service

Reference name of the Zone 2:web Service (child namespace of the Web service)

Zone 3: Action Add Web Reference

// The WebService service can be created directly in the project to invoke the method            New Webservice.dianwebservice ();            Web. HelloWorld ();            Web. AddFunction (12);

Note: The project that calls the WebService service cannot be the same project as the project that provides the WebService service, otherwise the remote call service is turned off by an exception when the code is being tested, You can use one project to invoke a service provided by another project (where the WebService service is mostly in the direction of a different address or port).

Method Two, invoking the service through a dynamic proxy

Create a service for a dynamic agent, and then call different WebService services directly based on the different parameters that are needed in the project

  Public classWebServices {/// <summary<        ///Instantiate WebServices/// </summary<        /// <param name= "url" <webservices address </param<        /// <param name= "methodname" < method of invocation </param<        /// <param name= "args" < put the parameters needed in WebServices in order in this object[] </param<Public Static Object Invokewebservice (string namespacename, String url, String methodname, object[] args)         {            //the namespace here is a reference to the WebServices namespace, where it is written dead, you can add a parameter from the outside to pass in.             if(string. IsNullOrEmpty (namespacename)) NamespaceName="servicewebtest"; Try            {                //get WSDLWebClient WC =NewWebClient (); Stream Stream= WC. OpenRead (URL +"? WSDL"); ServiceDescription SD=Servicedescription.read (stream); stringclassname = sd. services[0].                Name; ServiceDescriptionImporter SDI=NewServiceDescriptionImporter (); Sdi. Addservicedescription (SD,"",""); CodeNamespace cn=NewCodeNamespace (namespacename); //Generate the client proxy class codeCodeCompileUnit CCU =NewCodeCompileUnit (); Ccu.                Namespaces.add (CN); Sdi.                Import (CN, CCU); CSharpCodeProvider csc=NewCSharpCodeProvider (); ICodeCompiler ICC=CSC.                CreateCompiler (); //Setting Compilation ParametersCompilerParameters 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 classesCompilerResults CR =icc.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); }                    Throw NewException (sb.)                ToString ()); }                //build the proxy instance and call the methodSystem.Reflection.Assembly Assembly =cr.compiledassembly; Type T= assembly. GetType (NamespaceName +"."+ ClassName,true,true); Objectobj =activator.createinstance (t); System.Reflection.MethodInfo mi=T.getmethod (methodname); returnmi.            Invoke (obj, args); }            Catch            {                return NULL; }        }    }
Call  var objectuser = webservices.invokewebservice (namespacename, URL, methodname, new object[] in place where the service needs to be called; C10/>response.write (Objectuser);

  

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.