Sticker (Computer newspaper): Practical Guide for Web Service Development (Figure omitted)

Source: Internet
Author: User
Tags processing instruction servervariables

Web Service Development Guide
Romsan Appendix

The Web service platform is a set of standards that define how applications perform interactive operations on the web. You can write web services in any language you like on any platform, as long as we can query and access these services through web service standards.

This article uses the VB. NET platform to show you the methods and skills for Web service development.

I. Composition Technology of the Web Service Platform
1. What is Web service?
On the surface, Web Service is an application, an API that can be called through the Web (Application Programming Interface, Application Programming Interface ). That is to say, you can use a programming method and web call to implement a function application.

From a deeper perspective, Web Service is a new Web application branch. It is a self-contained, self-described, and modular application that can be deployed on the Network (usually Web) is described, published, searched, and called through the Web.

Web Service is a network-based, distributed modular component that executes specific tasks and complies with specific technical specifications. These specifications Enable Web service to interact with other compatible components. It can use the standard Internet Protocol to embody functions on the Internet and the enterprise intranet.

2. Composition Technology of the Web Service Platform
Generally, a Web Service consists of the following three major technical components:

(1) XML and XSD

XML (Extensible Markup Language) is the basic format for data representation on the Web service platform. XML solves the problem of data representation, but it does not define the standard data type, and does not define how to expand the data type. For example, what is the integer number? 16-bit, 32-bit, or 64-bit? These details are important for implementing interactive operations. XML Schema (XSD) developed by W3C is a set of standards dedicated to solving this problem. It defines a set of standard data types and provides a language to extend this data type. The Web service platform uses XSD as its data type system. When you use a programming language (such as VB. net or C #) to compile a web service application, to comply with the Web service standard, all the data types you use must be converted to the XSD type.

(2) soap

After the Web service application is compiled, we need to call it. Soap (Simple Object Access Protocol, Simple Object Access Protocol) provides standard RPC (Remote process call) method to call the web service. The SOAP specification defines the format of soap messages and how to use soap over HTTP. Soap is based on XML and XSD.

(3) WSDL

Web Service Description Language (WSDL) is an XML-based language used to describe Web services and their functions, parameters, and return values. Because it is based on XML, WSDL is machine readable and developer readable. Some of the latest development tools can generate a WSDL document based on your web service, and import the WSDL document to generate and call the corresponding web service code.

3. Web Service Workflow
The workflow of Web Service 1 is shown in.

 

When using web service, there are three stages of communication. In Figure 1, the three stages of communication process are listed. Stage 1 communication is called the discovery stage (discover). Its main function is to determine which services are available on the server.

During the discovery phase, we can determine which services the server provides in total. Before using these services, we must know what interfaces these services support. Therefore, the communication in the Web service stage 2nd is to send a request to obtain the Web Service Description Language (WSDL.

Stage 1 communication mainly sends information service requests to the Web Service server and waits for the server to respond.

Ii. Technical Elements of Web Service in. net
Using the class interface developed by. Net for web services, we can easily create a web service program. The following describes some major technical elements.

1. Web service processing commands
Web service processing commands provide necessary information for the ASP. NET environment, such as classes that implement the XML Web Services function. The following is an example of a Web Service Processing Instruction in the. asmx file:

<% @ WebService Language = "VB" codebehind = "service1.asmx. VB" class = "webservice1.service1" %>

The language attribute indicates the programming language used to develop XML Web Services. You can use any language compatible with. Net (such as VB. NET or C #) to create XML Web Services. The supported code files associated with the. asmx page are indicated by the codebehind attribute. Class Attribute indicates a class that supports the XML Web Services function in code files.

Note: To view the content of the. asmx file in Solution Explorer of. net, right-click the. asmx file and click the open mode command. In the "open mode" dialog box, select the "Source code [text] editor" option and click "open.

2. system. Web. Services. WebService class
System. web. services. the WebService class defines an optional base class for XML Web Services and provides direct access to common ASP.. Net object (such as application and session State objects) permission. By default, XML Web Services created using Visual Studio. net in the form of hosted code inherit this class. XML Web Services can inherit this class to obtain permissions to access inherent ASP. NET objects (such as requests and sessions.

If XML Web Services does not inherit this class, you can also access the inherent ASP. NET object through system. Web. httpcontext. Current. Classes that implement XML Web Services must be public and must have a common default constructor (a constructor without parameters ). In this way, ASP. NET can create an XML Web Services instance to process incoming XML Web Services requests.

3. WebService attributes
Each XML Web Service requires a unique namespace, which allows the client application to differentiate XML Web services that may use the same method name. The default namespace for XML Web Services created in Visual Studio. NET is http://tempuri.org ". Although a namespace is similar to a typical URL (Uniform Resource Identifier), it cannot be viewed in a Web browser and is only a unique identifier. WebService attributes mainly include the following attributes:

(1) Description attributes

The value of this attribute contains descriptive messages, which are generated in the XML Web Services Description file (such as the service description and service help page) and displayed to potential users of XML Web Services.

(2) name attribute

The value of this attribute contains the name of XML Web Services. By default, this value is the name of the class that implements XML Web Services. The name attribute identifies the local part of the XML qualified name of XML Web Services. The name attribute is also used to display the name of XML Web Services on the service help page.

(3) namespace attributes

The value of this attribute contains the default namespace of XML Web Services. The XML namespace provides a method to create a name in an XML document. The name can be identified by a URL. You can use an XML namespace to uniquely identify elements or attributes in an XML document. Therefore, in the service description of XML Web Services, namespace is used as the default namespace for XML elements directly related to XML Web Services. If you do not specify a namespace, use the default namespace "http://tempuri.org ".

The following sample code illustrates the usage of WebService attributes:

<WebService (namespace: = "http: // myserver/mywebservices /",_

Description: = "you can enter descriptive text here. ",

Name: = "myfavoritesservice")> _

Public class service1

Inherits system. Web. Services. WebService

'Implementation code

End Class

4. webmethod attributes
When creating XML Web Services with managed code, you can specify the methods available in XML Web Services by placing the webmethod Attribute before the public method declaration. The private method cannot act as the entry point of XML Web Services, although they can use the same class, and XML Web Services Code can call them. The webmethod attribute must be applied to each public method that can be used as part of XML Web Services.

The webmethod attribute contains several attributes for configuring XML Web Services behaviors. For example, you can use this attribute to provide a brief description on the service help page. The webmethod attribute provides the following attributes:

(1) bufferresponse attributes

When this attribute is set to true (default), ASP. NET caches the entire response before sending the response to the client. Cache is a very effective method. It can improve performance by reducing the communication between auxiliary processes and Internet Information Service (IIS) processes. When set to false, ASP. NET caches the response in the 16 KB block. Generally, this attribute is set to false only when you do not want to cache all the response content in the memory. For example, you are writing a set of multiple outbound databases. The default value is true unless otherwise specified.

(2) cacheduration attributes

The value of this attribute specifies the number of seconds required to set the result for each unique parameter in ASP. NET cache. The default value is 0 unless otherwise specified. This setting will disable result caching.

(3) Description attributes

The value of this attribute describes the XML Web Services method and is displayed on the service help page. Unless otherwise specified, the default value is a null string.

(4) enablesession attributes

When this attribute is set to false (default), ASP. NET cannot access the session Status of the XML Web Services method. When it is set to true, XML Web Services can be directly from httpcontext. current. the Session Access session state set. You can also use WebService when the basic WebService class is inherited. session attribute.

(5) messagename attributes

The value of this attribute enables XML Web Services to use aliases to uniquely identify overload methods. Unless otherwise specified, the default value is the method name. When a value is specified for messagename, The result SOAP message will reflect this name rather than the actual method name.

(6) transactionoption attributes

The value of this attribute specifies whether the XML Web Services method can be used as the root object of the transaction. Although the transactionoption attribute can be set to any value of the transactionoption Enumeration type, there are only two possible actions in the XML Web Services method: it is not involved in transactions (disabled, notsupported, and supported ), or create a new transaction (required and requiresnew ). Unless otherwise specified, the default value is transactionoption. Disabled. To use this attribute, you must add a reference to system. isiseservices. dll. This namespace contains methods and attributes that provide a distributed transaction model that can be found in the COM + service. The system. enterpriseservices. contextutil class allows you to set the transaction using the setabort or setcomplete method.

The following sample code illustrates the usage of the webmethod attribute:

Public class service1

Inherits system. Web. Services. WebService

<Webmethod (bufferresponse: = false ,_

Cacheduration: = 60 ,_

Description: = "Some descriptive words ",

Messagename: = "retrievedata")> _

Public Function getbigchunkofdata () as Dataset

'Implementation code

End Function

End Class

5. XML Web Services Discovery
XML Web Services Discovery is the process of locating and querying XML Web Services Instructions and the basic steps for accessing XML Web Services. By discovering a process, the XML Web Services Client can understand whether an XML Web Service exists, how it functions, and how to interact with it correctly in the design phase.

However, the Web site implementing XML Web Services does not need to support the discovery process, but another site is responsible for describing the service (such as the XML Web Services Directory ). In addition, there may be no public method available to search for a service, for example, when creating a dedicated service. XML Web Services Discovery mainly includes the following content:

(1) Static discovery (. Disco)

You can enable XML Web Services Program discovery by publishing the. disco file (an XML document that contains links to other discovery documents, XSD schemes, and service descriptions. XML Web Services automatically created using ASP. NET can provide generated discovery documents. For example, to access the XML Web Services Discovery document named service1.asmx (part of the webservice1 project in the Local Computer), you can use the following URL:

Http: // localhost/webservice1/service1.asmx? Disco

The following example shows the structure of the found document:

<? XML version = "1.0"?>

<Disco: discovery xmlns: Disco = "http://schemas.xmlsoap.org/disco"

Xmlns: WSDL = "http://schemas.xmlsoap.org/disco/wsdl">

<WSDL: contractref ref = "http: // MyWebServer/username. asmx? WSDL "/>

</Disco: discovery>

Note: A discovery document is an element container that usually contains a Resource Link (URL) that provides XML Web Services Discovery information ). If the URL is relative, it is assumed that they are relative to the location of the document found.

(2) Dynamic discovery (. vsdisco)

Dynamic discovery is the process in which ASP. Net performs iterative search to find available XML Web Services by developing the folder hierarchy on the Web server. Dynamic discovery (. vsdisco) files are XML-based files that can contain 0 or multiple nodes. Each node contains a path attribute. The path attribute contains the relative path pointing to the subfolders (subfolders that cannot be searched by the dynamic discovery process. The following is an example vsdisco file:

<? XML version = "1.0" encoding = "UTF-8"?>

<Dynamicdiscovery xmlns = "urn: Schemas-dynamicdiscovery: disco.2003-10-17">

<Exclude Path = "_ vti_cnf"/>

<Exclude Path = "_ vti_pvt"/>

<Exclude Path = "_ vti_log"/>

<Exclude Path = "_ vti_script"/>

<Exclude Path = "_ vti_txt"/>

<Exclude Path = "web references"/>

</Dynamicdiscovery>

When the dynamic discovery web server request. vsdisco file is enabled, a discovery document containing web service discovery information is returned for each web service that has been located through the dynamic discovery process.

By default, dynamic discovery is disabled in Web. config. To control which XML Web Services clients can discover services, only dynamic discovery should be used on the development web server. When deploying XML Web Services to the production Web server, you should create and publish a static discovery file (. Disco) for the XML Web Services that you want the client to discover ).

3. Detailed steps for creating a Web Service Program
For. net, Web Service is actually a server class. A method of this class is marked in a special way so that. Net can know which methods are published on the service. Readers can use the following simple program to learn more about the internal mechanism of Web Service in. net.

1. Creation steps
Create an ASP. NET web service-based project in Visual Studio. NET. Define the project name as demoservice.

After this step is completed, a new web site and a new web page service1.asmx of the site will be created. This page indicates a service, and a web service project can contain many different services. The global. asax and web. config files are generated at the same time to configure the Web environment.

In Solution Explorer, right-click service1.asmx and select the "view code" command. Then we can see that a "hello World" sample method is placed in web service. 2.

 

In the following example, we will expand it.

Run the project directly, as shown in result 3.

 

Click "helloword" to open another running method page. Click the "call" button to view the soap response returned from the server in the new window.

<? XML version = "1.0" encoding = "UTF-8"?>

<String xmlns = "http://tempuri.org/"> Hello World </string>

Code Description:

In Web Service, each. asmx page is followed by a class. This class is where the helloworld method is located, from the code shown in Figure 2:

Public class service1

Inherits system. Web. Services. WebService

We can find that this class inherits from system. Web. Services. WebService. This class is used to give the page that the user clicks in Internet Explorer and call the helloworld method. The webmethod attribute tag is used to indicate that a method acts on the Web service class.

2. Add more methods
Now let's build some new methods for demoservice to illustrate the actual work of web service.

Open the code editor of service1.asmx and write the following code in the helloworld method:

<Webmethod ()> Public Function newtest (byval number as double) as double

Return math. SQRT (number)

End Function

Note: This method is used to obtain the square root of a number.

Compile and run the program again. Run Result 4:

 

Click the "newtest" link. 5.

 

Enter the number "121" in the "Number" box and click "call". The soap response information is as follows:

<? XML version = "1.0" encoding = "UTF-8"?>

<Double xmlns = "http://tempuri.org/"> 11 </Double>

Through the above demonstration, we can easily find that building a simple Web Service is not complicated. The following describes how to build a web service through a specific instance.

Iv. instance resolution-compare the sizes of two numbers with Web Services
We have learned how to create a Web Service server through the previous introduction. This example focuses on how to access the Web service, that is, how the user end interacts with the web service.

1. instance details
Create a web service project named "themax ". The creation method and steps are described in this article. The core code is provided directly in the instance.

<Webmethod ()> Public Function maxnum (byval number1 as integer, byval number2 as integer) as integer

Dim Number3 as integer

If number1-number2 <0 then Number3 = number1 else Number3 = number2

Maxnum = Number3

End Function

Result 6 of running the program is as follows:

 

Enter two numbers in the number1 and number2 boxes, for example, 87 and 98. Click the "call" button. The following result is displayed:

<? XML version = "1.0" encoding = "UTF-8"?>

<Int xmlns = "http://tempuri.org/"> 98 </int>

After completing the preceding steps, our Web Service is successfully built.

2. Web Service Access
Generally, you can access a web service in two ways: Windows application access and web application call access.

Create a Windows application and name it "themax", as shown in figure 7.

 

Now, let's create a "Web reference ". This is the most important and key step. In Solution Explorer, right-click the project name themax and select the Add web reference command. In the address bar, enter the URL to access web servie: http: // localhost/themax/service1.asmx.

If "Web reference" is created correctly, a web references folder is automatically generated in "Reference" of "solution Resource Manager. There is a globe icon under this folder, followed by the Web Service server name. Double-click the command button and enter the following code:

Private sub button#click (byval sender as system. Object, byval e as system. eventargs) handles button1.click

Dim maxnum as string

Dim themax as new localhost. service1 ()

Dim number1 as integer = Val (textbox1.text)

Dim number2 as integer = Val (textbox2.text)

Maxnum = themax. maxnum (number1, number2)

Label3.text = "the maximum number is:" & maxnum

End sub

Compile and run the program. The running result is 8.

 

When a Windows application calls a web service program, it must retain the WSDL file backup locally to describe the called Web service program. Based on the information provided by the WSDL file, Visual Studio. Net IDE can verify whether the parameter type passed to the Web service program is correct and whether the data type returned to the Windows application matches.

3. web program call access
Web applications are inherently capable of accessing Web service programs. Because both programs rely on the Internet for communication. Next, we will introduce how web programs access web services.

Create a web application project and name it webthemax. Click web form to set the pagelayout attribute to "gridlayout ". Design the program interface as shown in Figure 9.

 

Add web references in the same way as Windows applications. Double-click the Compare button and enter the following code:

Private sub button#click (byval sender as system. Object, byval e as system. eventargs) handles button1.click

Dim maxnum as string

Dim themax as new localhost. service1 ()

Dim number1 as integer = Val (textbox1.text)

Dim number2 as integer = Val (textbox2.text)

Maxnum = themax. maxnum (number1, number2)

Label3.text = maxnum

End sub

Compile and run the program. Enter 45 and 54 in the two boxes, and click "Compare" to get the corresponding result.

By introducing the two web service access methods, we can easily find that the methods and steps for implementing these two methods are basically the same. The core content is "Adding web references ". Only by correctly establishing the link between the client and the server can we smoothly exchange data. This is also the top priority for Building Web service programs.

V. instance resolution-create a folder Viewer
Based on the example above, we have basically learned how to create a web service program and how to access it. Now, we will introduce how to build a web service server through a relatively complex web service program.

Purpose of this example: Create a folder viewer to list all subfolders in the specified directory.

We first provide the instance code, and then perform a detailed analysis.

Create a new ASP. NET web service project and name it pictureservice.

Create a new "pictures" folder under the service root directory c:/inetpub/wwwroot/pictureservice, and create two subfolders named mypicture and youpicture respectively.

Enter the following code in the service1.asmx Code Editor:

Imports system. Web. Services

Imports system. Io

Automatically generate code.

Public readonly property picturefolerpath () as string

Get

Dim asmxpath as string, picturepath as string

Asmxpath = server. mappath (context. Request. servervariables. Item ("script_name "))

Dim N as integer

For N = asmxpath. Length-1 to n step-1

If asmxpath. Chars (n) = "/" C then

Dim serverpath as string = asmxpath. substring (0, n)

Picturepath = serverpath & "/pictures"

Exit

End if

Next

Return picturepath

End get

End Property

Public readonly property picturefolder () as directoryinfo

Get

Return new directoryinfo (picturefolerpath)

End get

End Property

Public Function getpicturefolders () as string ()

Dim picturefolder as directoryinfo = me. picturefolder

Dim picturesubfolders () as directoryinfo = picturefolder. getdirectories ()

Dim Foldername (picturesubfolders. Length-1) as string

Dim picturesubfolder as directoryinfo, index as integer

For each picturesubfolder in picturesubfolders

Foldername (INDEX) = picturesubfolder. Name

Index + = 1

Next

Return Foldername

End Function

End Class

Run the program. The result is as follows:

<? XML version = "1.0" encoding = "UTF-8"?>

-<Arrayofstring mlns: XSD = "The http://www.w3.org/2001/XMLSchema" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://tempuri.org/">

<String> mypicture </string>

<String> youpicture </string>

</Arrayofstring>

The above code is analyzed below:

To list all subfolders in a specified folder, you must first obtain the complete path of the file. In this example, we first create a picturefolderpath attribute to obtain the complete path C:/inetpub/wwwroot/pictureservice/servcie1.asmx for the service. asmx file that supports the entire service. In the program, we use the following code to achieve this:

Dim asmxpath as string, picturepath as string

Asmxpath = server. mappath (context. Request. servervariables. Item ("script_name "))

However, this is not our goal. Our ultimate goal is to get the complete path of the "pictures" file. Since we put the file service1.asmx and the Pictures folder under the same file, we only need: replace service1.asmx with pictures in/inetpub/wwwroot/pictureservice/servcie1.asmx.

Code segment:

Dim N as integer

For N = asmxpath. Length-1 to n step-1

If asmxpath. Chars (n) = "/" C then

Dim serverpath as string = asmxpath. substring (0, n)

Picturepath = serverpath & "/pictures"

Exit

End if

Next

Return picturepath

Is used to implement this function.

After the above two sections of code are run, we have obtained the expected result, that is, the complete path of the Pictures folder is C:/inetpub/wwwroot/pictureservice/servcie1.asmx.

Now let's look back at the beginning of the Code. In this program, we introduce a new namespace system. Io. We will use its class interface system. Io. directoryinfo to get the folder information. In the following code, we construct a new property pictturefolder to return the information of the specified folder in picturefolderpath.

Public readonly property picturefolder () as directoryinfo

Get

Return new directoryinfo (picturefolerpath)

End get

End Property

After the above Code is completed, we have obtained information about the specified folder. Finally, create a web service method to return results.

Public Function getpicturefolders () as string ()

Dim picturefolder as directoryinfo = me. picturefolder

Dim picturesubfolders () as directoryinfo = picturefolder. getdirectories ()

Dim Foldername (picturesubfolders. Length-1) as string

Dim picturesubfolder as directoryinfo, index as integer

For each picturesubfolder in picturesubfolders

Foldername (INDEX) = picturesubfolder. Name

Index + = 1

Next

Return Foldername

End Function

Through instance analysis, we can see that a complex web service program contains a wide range of content. This article only focuses on some things on the surface of web service programs. The technical points of essence need to be explored by readers.
 

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.