Write a simple web service

zhaozj2021-02-16  49

Write a simple web service

Author: cultivate (innocent) QQ: 24149877 Time: 2003.6.14 night

Before starting the following example, your system needs: 1, win2000 Iis; 2, vs.net; 3, SQL Server (I used SQL database);

The example of this web service is written by MS big blow. If you like VB, then use VB is also the same, you only have some small differences on the syntax, but just MS is advocated. C #, if you can use C # write or use this is ok.

Here is the steps:

First, open VS. NET's integrated development environment, Select New on the File menu, create a new C # ASP.NET Web Service Engineering, the project is called WebServicedemo (complete http: // localhost / webserviceDemo). This is VS to generate the corresponding file in your web system directory, my service directory is the default C: / INETPUB / WWWROOT, the generated file is in C: / INETPUB / WWWROOT / WebServicedemo, there is not much to say .

Second, open the C # source file corresponding to the generated project, here is Service1.asmx.cs, the vs.net integration environment has generated the corresponding code for you as follows: // ============= ============================================================================================================================================================================================================= ============== // file: Service1.asmx.cs // description: a Web Service architecture to the database // author visits: cultivate (innocent) // time: 2003.6.14 // ============================================== ================================

using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Web; using System.Web.Services; using System.Data.SqlClient; // system generates and project name The same namespace Namespace WebServiceDemo {///

/// Summary Description for service1. /// // All Web services are derived from System.Web.Services.Webservice. Public class service1: system.web.services.Webservice {public service1 () {// codegen: this call is required by the ASP.NET Web Services designer initializecomponent ();

I have added a file instructions and corresponding comments, and next is to write the corresponding service code inside. Here I would like to first package the operation of the database in a separate class of the same namespace. You can use the corresponding method in this class when you write a Web method. Here is the code I wrote:

/ / -------------------------------------------------------------------------------------------- ------------------------- // Build a new class for access to data / / / ---------- -------------------------------------------------- ------------- public class DataAccess {// connection string member variable private string m_szConn = ""; private SqlConnection m_sqlConn; private SqlDataAdapter m_sqlDa; // constructors public DataAccess (string szConnectionString) { M_szconn = szconnectionstring;} // Return a recordset PUBLIC DATASET GETDATASET (String Szcommandtext) {DataSet Sqlds;

try {m_sqlConn = new SqlConnection (m_szConn); m_sqlConn.Open (); m_sqlDa = new SqlDataAdapter (szCommandText, m_sqlConn); sqlDs = new DataSet (); m_sqlDa.Fill (sqlDs); m_sqlConn.Close (); return sqlDs;} catch {return null;}} // overloaded above process public DataSet getDataset (string szCommandText, string szTableName) {DataSet sqlDs; try {m_sqlConn = new SqlConnection (m_szConn); m_sqlConn.Open (); m_sqlDa = new SqlDataAdapter (szCommandText, m_sqlconn; sqlds = new dataset (); m_sqlda.close; m_sqlconn.close (); return sqlds;} catch {return null;}}} These don't say more, and create a general C # class it's the same. There are three functions in the class, one of which is incorporated into the connection string when the call is called. The other two functions are the same role, returning to the record set required by the user, only the parameters of the passage are not the same, the essence is the same.

Below is the code that is truly used for web calls in the service1 class, which is something called web application. Before writing this class, you should first apply for a service command space, set the corresponding attribute, this sentence can not be less, huh, it tells the path to the web service. As follows: // Declare a service space [Webservice (Namespace = "http: // LocalHost / WebServicedemo /", in fact, this is the most important thing ~, other you can don't, Name = "Web service demo", Description = "Web Service Demo"] below is the code of Service1:

Public class service1: system.Web.Services.Webservice {public service1 () {// codegen: this call is required by the asp.net web services designer initializecomponent ();

#region Component Designer generated code // Required by the Web Services Designer private IContainer components = null; ///

/// Required method for Designer support - do not modify /// the contents of this method with the code editor . /// private void initializecomponent () {}

///

/// clean up any resource> protected {components.dispose () {components.dispose () {components.dispose () {components.dispose () {components.dispose (); .Dispose (Disposing);} # endregion // Connection string constance const string szconn = "server = (local) // taoyi; uid = sa; pwd =;" "Initial catalog = mydata; data source = taoyi";

[WebMethod] public string About () {return "This is a C # written Web Service demo!";} // Return to one of the WebServiceDemo table [WebMethod] public dataset getServicedemotable () {DataSet Sqlds = new dataset (); dataaccess DataAcc = New DataAccess (Szconn); String Szsql = "Select * from WebServicedemo"; SQLDS = DataAcc.getDataSet (SZSQL, "DEMO");

return sqlDs;} // Returns the query specified by the user [WebMethod] public DataSet GetByUser (string szCommandText) {DataSet sqlDs = new DataSet (); DataAccess dataAcc = new DataAccess (szConn); sqlDs = dataAcc.GetDataset (szCommandText);

Return Sqlds;}} is not very simple, just this, huh, huh ~, but you can explain the problem. This class declares three web methods, is there any found? [WebMethod] is added in front of each method, indicating that the method is a web method. Oh, if you want the function you write to let the web application call, this can not be less ~, otherwise the web application cannot be called.

When this web service is completed, click to run, if there is nothing wrong, there will be the following web page service description:

Service1

The Following Operations Aresu Supported. For a formal definition, please review the service description.

* GetByuser

* GetServicedemotable

* About

..... (there are still a lot below)

Among them, as an asterisk is a function of the [WebMethod] before the function. In the page you can click on the corresponding function, then you can jump to the call page, you can enter the corresponding parameters in the corresponding text box (if the function is parameter), click the button, then call the button, then you can see The result returned to the function (provided that the function call is not wrong), but all the text in the XML format. For example, my getServicedemotable function call is as follows:

- - - - - - - < / xs: complexType> - - - 1 TAOYI Male Sichuan Cangzhou - 2 xiner Female

Sichuan Yibin The Web Service program is already completed.

Here is what you want to write a web application to test the web service I wrote, see if you can achieve the result. The steps to establish a web application are as follows:

1. Create a new ASP.NET Web Application project, just as the first step in creating Web Service, just the type of engineering is not the same. I hereby an engine named WebServicedemotest, completely http: // localhost / webserviceDemotest, and generated the required files under the corresponding directory (C: / INETPUB / WWWWROOT / WebServicedemotest). Second, open the webform1.aspx file in the design view, placed a PANEL container inside, in order to achieve the purpose of the test, we need three server buttons and one server text box, call our three written in Web Service. Function, in addition, in order to display the data obtained by the calling method, a server tag control and a DataGrid control are also required. The layout of the page is casual, I want to place it, how to place it, as long as it can achieve the purpose of the demo. Third, refer to the previously written Web Service program, the menu steps are as follows Project-> Add Web Reference ..., then enter our web service path, here is http://localhost/webserviceDemo/service1.asmx, click Add to OK . At this point you will see the localhost namespace in the class view. Fourth, write test code.

In order to make it easier to write some code, such as (xxxx.xxx.xx xx = new xxxx.xxx.xx ()), then you have to quote the service1 class in the localhost namespace, and write xxxx xx = new xxxx directly after It is ok. Here is the code of several buttons:

// Test GetServicedemotable () Private Void Button2_Click (Object Sender, System.EventArgs E) {DataSet DS = New Dataset (); service1 oservice = new localhost.service1 ();

// Return record set DS = oservice.getServiceDemotable (); if (ds! = Null) {// Display record set record DataGrid1.datasource = DS.TABLES ["demo"]; DataGrid1.Database ();} else { THIS.RESPONSE.WRITE ("Load Data Error!");}} // Test getByuser () private void button1_click (object sender, system.eventargs e) {dataset ds = new dataset (); service1 oserce = new localhost.service1 (); String szcommand = textBox1.text; ds = oservice.getByuser (szcommand); if (ds! = Null) {dataGrid1.datasource = DS; DataGrid1.database ();} else response.write ("error! Map Is the SQL command has problems! ");} // Test About () private void button3_click (Object sender, system.eventargs e) {service1 oservice = new localhost.service1 (); label1.text = oservice.about ();}

OK, the end is running, if everything is OK, click the first button to get the table result of the SQL command executed in a package letter user. The second button is getting the XML description gets above the topserviceDemotable when running Web Service, i.e. Id Szuser Szsex Szaddr 1 TAOYI Male Sichuan, Sichuan 2 Xiner Female Sichuan Yibin Click on the third button, displayed in Label1 "This is a C # Written Web Service Demo! "String.

Ok, everything is OK. What is wrong place, welcome to correct!

转载请注明原文地址:https://www.9cbs.com/read-24358.html

New Post(0)