WebService creating and using

Source: Internet
Author: User

Because the project needs to implement the client-server data exchange, as well as to obtain the analysis results of other server-side programs, so the WebService do some simple understanding, is now recorded as follows:

I. Preparation of WebService Program

1. Create a new blank site in VS

2. Add a new item to the blank site and select "Web Service"

3, in the Web service to write to the client side to provide interface functions, I am here to write a simple two read the contents of a TXT document in the server and return the function.

1[WebService (Namespace ="http://tempuri.org/")]2[WebServiceBinding (ConformsTo =wsiprofiles.basicprofile1_1)]3[System.ComponentModel.ToolboxItem (false)]4     //to allow the Web service to be called from the script using ASP. NET AJAX, uncomment the downstream. 5     //[System.Web.Script.Services.ScriptService]6      Public classProject3DInfoService:System.Web.Services.WebService7     {8 9[WebMethod (Description ="Fuzzy Matching")]Ten          Public stringGetprojectbaseinfofuzzyquery (stringprjname) One         { A             stringTxtfilename =@"D:\NJ3DGIS\JsonStrs.txt"; -             stringJsonstr =File.readalltext (Txtfilename, encoding.default); -             returnJsonstr; the         } -  -[WebMethod (Description ="Exact Match")] -          Public stringGetprojectbaseinfo (stringprjname) +         { -             stringTxtfilename =@"D:\NJ3DGIS\JsonStr.txt"; +             stringJsonstr =File.readalltext (Txtfilename, encoding.default); A             returnJsonstr; at         } -}

Ii. WebService Release Here is an example of the simplest common IIS release

1. Open IIS Manager, right click on [application Pool], add application pool, and note select the. NET Framework version. You can also use an existing application pool directly.

2. Right-click an existing Web site, select Add Application, set the physical path of the application to the folder where the WebService program resides, and the file directory to the folder level where the Asmx file is located. and set other parameters.

3. After the setup is complete, right-click on the newly added application [admin application]-[] to see the function you wrote, and enter the parameters to view the returned results.

Note: If the browser displays an HTTP error 403.14–forbidden, in the IIS Manager feature view interface, select Go to [Directory Browsing] and click [Start] on the rightmost panel.

Third, the customer service side call WebService

The customer service side can call webservice across languages, there are many methods to invoke.

1. Add a service Reference

«Right click Project Program [Reference]-Add service reference. In the Popup form interface, select [Advanced]-[Add Web Reference], enter the WebService address in the URL column (that is, the browser displays the address when [browse], the locahost to the server IP: Port number), click [Add Reference] to complete the add;

After adding a service reference

«After adding a service reference, you can directly invoke the interface function provided by WebService. But to make the program portable, we can write the WebService reference address in the configuration file, setting the URL of the service reference from the read value in the configuration file. This is done by modifying the Reference.cs (which can be found in a local file, or F12 into the class name of the service) in the code. The value of Url= "is set to read from the configuration file. This allows you to modify the corresponding URL values in the configuration file whenever the server IP changes or needs to be deployed elsewhere.

This method is the simplest, but obviously not very practical.

2, WebService Packaging

«webservice Package Build DLL can refer to this blog

http://blog.csdn.net/gxxloveszj/article/details/8332584

The DLL call interface function can be added directly after the «webservice package, and no service references need to be added, but each time the server has changed it needs to be repackaged once.

3. Dynamic invocation of Web services

The dynamic invocation of the Web service requires only the WebService writer to provide the Web service URL and function name, which involves some reflection, CodeDom, programming using C # compiler knowledge, it is cumbersome but easy to use, please refer to the blog.

Http://www.cnblogs.com/chenmfly/p/4463422.html

The code is as follows, where the URL is the address of the Web service, MethodName is to invoke the service method name, args is the parameter to invoke the Web service, and the return value is the result of the Web service's return.

  Public Static ObjectInvokewebservice (stringUrlstringMethodNameObject[] args) {           returnInvokewebservicemy (URL,NULL, MethodName, args); }        Public Static ObjectInvokewebservicemy (stringUrlstringClassNamestringMethodNameObject[] args) {           string@namespace ="EnterpriseServerBase.WebService.DynamicWebCalling"; if(ClassName = =NULL) || (ClassName = ="") ) {classname=getwsclassname (URL); }           Try           {               //get WSDLWebClient WC =NewWebClient (); Stream Stream= WC. OpenRead (URL +"? WSDL"); ServiceDescription SD=Servicedescription.read (stream); 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"); //compile the proxy class; CompilerResults 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 ()); }               //generates a proxy instance and invokes a method; System.Reflection.Assembly Assembly =cr.compiledassembly; Type T= assembly. GetType (@namespace +"."+ ClassName,true,true); Objectobj =activator.createinstance (t); System.Reflection.MethodInfo mi=T.getmethod (methodname); returnmi.           Invoke (obj, args); }           Catch(Exception ex) {Throw NewException (ex. Innerexception.message,NewException (ex.           Innerexception.stacktrace)); }       }       Private Static stringGetwsclassname (stringWsurl) {           string[] parts = Wsurl.split ('/'); string[] pps = Parts[parts. Length-1]. Split ('.'); returnpps[0]; }  

In addition, you can use HttpWebRequest and other methods to dynamically invoke Web services, there are a lot of detailed information on the Internet, not posted here.

WebService creating and using

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.