How to create and use a web service [Post]

Source: Internet
Author: User
How to create and use Web Services
Author: Meng xianhui: [wonderful world of Meng xianhui ]--------------------------------------------------------------------------------
 
Introduction

One of the most powerful aspects of. NET is that it can be used to create Web Services. A Web Service is an external interface provided by a website for calls by other websites. For example, a financial company can provide detailed stock quotations with its trading partners through web services. Such information can be read and displayed on the web page, it can also be read from customers' desktop applications.

This article describes two aspects of Web Services: How to Create web services and how to use web services. As an example, we have since aspfaqs.com (http://www.aspfaqs.com/aspfaqs/) FAQs (FAQ) web services to explain how to create a web service.

Create a Web Service

Before creating a Web service, you must first ask yourself: "What services do I want to provide to my users ?". The goal of this article is to create a web service that allows other users to display a list of FAQ (FAQs) from aspfaqs.com on their own websites. The ideal function is to restrict other websites to only view FAQs categories and FAQs by category. If you want to view the answer to a question, it allows users to access the http://www.aspfaqs.com of the website that provides services. The Web service in this example provides the following functions to other websites:

1. Browse the list of all FAQ categories
2. Browse all FAQs in a category.
3. Browse a FAQ, but do not include answers.
It is easy to create a web service. First, create a web service. asmx file (you can use Visual Studio. net or any text editor you like. We recommend that you use web matrix, which has templates for creating web services.) Web services are created as common classes, there is a macro in front of the method, indicating that this method is accessed through Web Services.

For the aspfaqs.com web service, first create three methods for access through the Web service, getcategories, getfaqsincategory, and getfaq, respectively to implement the preceding tasks 1, 2, 3. Create a private method getdataset and assemble it into a dataset Based on the passed SQL query. The following is the implementation code:

<% @ WebService Language = "VB" class = "aspfaqs" %>
Imports system. Web. Services
Imports system. Data
Imports system. Data. sqlclient
Imports system. Configuration
 
Public class aspfaqs
 
'Create a private function methodgetdataset
Private function getdataset (strsql as string) as Dataset
'1. Create a sqlconnection connection object
Dim myconnection as new sqlconnection (connectionstring)
 
'2. Create a command object and input SQL parameters.
Dim mycommand as new sqlcommand (strsql, myconnection)
 
Myconnection. open ()
 
3. Create a dataadapter object
Dim mydataadapter as new sqldataadapter ()
Mydataadapter. selectcommand = mycommand
 
4. Generate dataset and close the connection
Dim mydataset as new dataset ()
Mydataadapter. Fill (mydataset)
Myconnection. Close ()

'Return Dataset
Return mydataset
End Function

'Create a method to implement three tasks
<Webmethod ()> Public Function getcategories () as Dataset
Return getdataset (SQL query) 'Here the parameter SQL is used to get all FAQ categories
End Function
 
 
<Webmethod ()> Public Function getfaqsincategory (catid as integer) as Dataset
Return getdataset (SQL query) 'Here, the parameter SQL is used to obtain all the FAQs about a category (catid ).
End Function

 
<Webmethod ()> Public Function getfaq (faqid as integer) as Dataset
Return getdataset (SQL query) 'Here the parameter SQL is used to obtain the information of a FAQ (faqid ).
End Function
End Class
As mentioned above, all three methods accessed through web services have a leading character. In the first line of the. asmx file, there is a @ WebService indicating the language and class name used. This Web Service is named aspfaqs and has the same name as the class. Once the. asmx file is created, it is saved to a directory that can be accessed through the web, and then accessible through the Web browser. For example, if the web service file is named aspfaqs. asmx and saved to the/WS directory, anyone can.

Note: When calling a web service method that requires parameters, you do not have to worry about the type of the input parameter. The web service code automatically ensures the correctness of the input parameter type, in the preceding example, the parameter type is integer. If a malicious user attempts to pass a parameter like 0' malicous SQL statement to the Web service, the system will return an error message: annot convert 0 'malicious SQL to system. int32. Parameter Name: type --> input string was not in a correct format. However, if you input a string type parameter, you should remember to replace a single marker (') with two consecutive marker ('').

Use Web Services

We have created a web service. Next we will look at how other websites use this web service. For convenience, we call the customer website that uses Web Services "consumers" and the website that provides Web Services "Producers ". The most essential thing is that the consumer must know what method to call the producer. If parameters are required, these parameters must be converted to XML format for input. The consumer sends an HTTP request to the producer and specifies the method and parameters to be called, parameters can be transmitted through a SOAP request in the form of querystring or a POST request header.

After receiving the sent request, the producer unpacks the input parameters and calls an appropriate method of the specified class. If the call is complete, the result is returned, packaged, and sent back to the consumer. When the consumer receives the response and unpacks it, the Web Service is called.

Obviously, we don't have to worry about the semantics of the sent HTTP information when using web services. To achieve this purpose, we can use a class called proxy, proxy acts as an intermediate process between a consumer application or web page and the actual Web Service of the producer. For each method of the producer Web Service, there is also an identical method in the proxy class. The proxy is responsible for processing all the transmitted complex messages, this complexity is hidden in the proxy class. We only need to simply call the method of this class without having to worry about semantics.

You may be confused at this time, but this confusion is understandable. This is a very confusing topic. The most basic thing to understand is that the HTTP Communication between the consumer and the producer may be complicated when the web service is called, and a lot of code may be required. We would like to see that calling a web service on a Web Service Page is as convenient as using a local component. To achieve this goal, we use the proxy class, its public interface corresponds to the Web service method. If you are still confused at this time, please refer to this demonstration document http://aspnet.4guysfromrolla.com/code/consumews.ppt, which will explain to you how to use web services.

Use Visual Studio. NET to create a proxy class

In Visual Studio. it is easy to create the proxy class used by Web Services in ASP. NET. in the. NET web project, right-click "Reference" and select "add web reference". A dialog box is displayed, asking you to enter a URL address, enter references (as you can see in your web browser), and click Add reference. net will automatically create a proxy class for you and compile it. When you add it to your project, the namespace of the proxy class may be your website address, such as com.4guysfromrolla. ASPnet, of course, you can change it to any other name. Calling web services from your web page through the proxy class is as convenient as calling using local components. Suppose you want to display ASP. net category (Category ID is 22) FAQs list, we can call the getfaqsincategory method of the web service, input 22 in the parameter, and bind the returned dataset to a DataGrid, the code may be written as follows:

'. Other HTML content on the ASPX page ......
<Asp: DataGrid id = "dgcategoryfaqs" runat = "server"/>
 
Private sub page_load (sender as object, e as eventargs)
'Create proxy class instance
Dim consumewebservice as com. _ 4guysfromrolla. ASPnet. aspfaqs
Set consumewebservice = new COM. _ 4guysfromrolla. ASPnet. aspfaqs

'Bind the getfaqsincategory result to dgcategoryfaqs
Dgcategoryfaqs. datasource = consumewebservice. getfaqsincategory (22)
Dgcategoryfaqs. databind ()
End sub
Check the above code. You may not understand. _ 4guysfromrolla. ASPnet. the aspfaqs proxy class is actually called by a remote web service. When the proxy class's getfaqsincategory method is called, complicated data communication (HTTP Request/Response) is performed ).

Conclusion

This article describes how to create a web service and use it on an ASP. NET page. Microsoft has actually simplified the process of creating and using Web Services in. net. To create a web service, simply create a. asmx file, write a little code for the Web service method, and add a macro. The code looks the same as the local component code. The use of web services is also very simple, thanks to the use of proxy classes. As mentioned above, using tools such as Visual Studio. NET to create a proxy class is also very simple.

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.