Use Visual Studio to create a new web service and then add methods to expose the functionality required for your web service.
To create the new web service:
On the Visual Studio .NET File menu, choose New→ Project....
When the New Project dialog box is displayed, go to the left pane and select either Visual Basic Projects or Visual C# Projects.
Go to the right pane and click on the ASP.NET Web Service icon.
Enter the name of the web service in the Location text box and click OK.
Visual Studio .NET creates a virtual directory in IIS and a project
that contains a .asmx
file and code-behind files
for the web service, like those shown in Example 11-2 through Example 11-5. The web
service is fully functional at this point but is just a shell with no
useful functionality.
You need to add methods to the code-behind to expose the functionality required for your web service. The code-behind shown in Example 11-6 (VB) and Example 11-7 (C#) shows a method we have added to our example web service to return a list of books from a database. The code generated by Visual Studio .NET to support the component designer has been omitted from Example 11-6 and Example 11-7 for clarity.
You can add a web service to an existing web application by selecting the project in the Solution Explorer, and then selecting Add New Item from the File menu. When the Add New Item dialog box is displayed, select Web Service, enter the desired name of the web service, and click Open. Any number of web services can be added to a web application.
Web services are a useful tool for communicating with remote systems or with systems built with technologies different from those used to build your application.
Visual Studio .NET greatly simplifies the creation of web services. With just a few menu selections, you can quickly build a web service shell that you can use to create the functionality required by your application.
In .NET, a web service consists of an .asmx
file
and a code-behind class that provides the required functionality. The
content of an .asmx
file consists of a single
line that contains a WebService
directive. The
line is just like the @ Page
directive used in the
.aspx
file, but with Page
replaced by WebService
:
<%@ WebService Language="vb" Codebehind="CH11QuickWebServiceVB1.asmx.vb" Class="VBWebServices.CH11QuickWebServiceVB1" %> <%@ WebService Language="c#" Codebehind="CH11QuickWebServiceCS1.asmx.cs" Class="CSWEbServices.CH11QuickWebServiceCS1" %>
The code-behind file for a web service consists of a class that
inherits from System.Web.Services.WebService
.
Public Class CH11QuickWebServiceVB1
Inherits System.Web.Services.WebService
...
End Class
public class CH11QuickWebServiceCS1 : System.Web.Services.WebService
{
...
}
In addition, Visual Studio .NET adds a WebService
attribute to the class definition. While not explicitly required, the
WebService
attribute lets you define the namespace
for the web service. By default, the namespace is set to
http://tempuri.org/, but you will typically want
to set this to the URI representing your company, such as
http://www.dominiondigital.com/.
<WebService(Namespace:="http://tempuri.org/ ")> _
Public Class CH11QuickWebServiceVB1 Inherits System.Web.Services.WebService ... End Class[WebService(Namespace="http://tempuri.org/")]
public class CH11QuickWebServiceCS1 : System.Web.Services.WebService { ... }
Other than the constructor it creates for the class, all of the code added by Visual Studio .NET is necessary to support the Web Services Designer and is not required for the web service itself.
To add useful functionality to the web service, you create methods
just as you would for any other class, except that you precede each
method definition with a WebMethod
attribute. The
WebMethod
attribute informs Visual Studio that the
method is to be exposed as part of the web service.
For instance, the getBookList
method shown in our
example queries a database for a list of books and returns the list
in a DataSet
. The number of books retrieved is
defined by the numberOfBooks
parameter. Nothing
special is done in the code to support the web service. Visual Studio
.NET and the .NET Framework take care of the creation of the XML and
the SOAP wrapper used to transfer the data to the client.
One of the big advantages to creating web services with Visual Studio .NET and ASP.NET is the testing and debugging functionality provided. ASP.NET provides a series of web pages that effectively create a test harness that can be used to test all the exposed methods of the web service. Visual Studio .NET lets you set breakpoints in your web service code so you can step through it to verify its operation.
To test a web service, run your project in Visual Studio .NET in
debug mode and access the .asmx
file for the web
service. ASP.NET will display a page listing all of the methods
exposed by the web service, as shown in Figure 11-1.
In this example, clicking on the getBookList
method displays another page where you can enter the required
numberOfBooks
parameter value and invoke (execute)
the method. Although not shown in Figure 11-2, this
page also displays the content of the XML-encoded request and
response messages for the method using SOAP, Http Get, and Http Post.
These samples allow you to examine the data that is exchanged when
the method is called.
When you click the Invoke button, ASP.NET generates an Http Get
request and submits it to the web service. The web service responds
with an Http response containing the requested data. In our example,
the XML shown in Example 11-1 is returned from the
web service when the numberOfBooks
parameter is
set to 10.
Example 11-1. XML returned with numberOfBooks parameter set to 10
<?xml version="1.0" encoding="utf-8"?> <DataSet xmlns="http://www.dominiondigital.com"> <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="NewDataSet" msdata:IsDataSet="true"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="Table"> <xs:complexType> <xs:sequence> <xs:element name="Title" type="xs:string" minOccurs="0" /> <xs:element name="ISBN" type="xs:string" minOccurs="0" /> <xs:element name="Publisher" type="xs:string" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"> <NewDataSet xmlns=""> <Table diffgr:id="Table1" msdata:rowOrder="0"> <Title>.Net Framework Essentials</Title> <ISBN>0-596-00302-1</ISBN> <Publisher>O'Reilly</Publisher> </Table> <Table diffgr:id="Table2" msdata:rowOrder="1"> <Title>Access Cookbook</Title> <ISBN>0-596-00084-7</ISBN> <Publisher>O'Reilly</Publisher> </Table> ... <Table diffgr:id="Table10" msdata:rowOrder="9"> <Title>HTML & XHTML: The Definitive Guide</Title> <ISBN>0-596-00026-X</ISBN> <Publisher>O'Reilly</Publisher> </Table> </NewDataSet> </diffgr:diffgram> </DataSet>
Example 11-2. Quick web service .asmx file (.vb)
<%@ WebService Language="vb" Codebehind="CH11QuickWebServiceVB1.asmx.vb" Class="VBWebServices.CH11QuickWebServiceVB1" %>
Example 11-3. Quick web service code-behind (.vb)
Imports System.Web.Services Namespace VBWebServices <WebService(Namespace:="http://tempuri.org/ ")> _ Public Class CH11QuickWebServiceVB1 Inherits System.Web.Services.WebService ' WEB SERVICE EXAMPLE ' The HelloWorld( ) example service returns the string Hello World. ' To build, uncomment the following lines then save and build the project. ' To test this web service, ensure that the .asmx file is the start page ' and press F5. ' '<WebMethod( )> _ 'Public Function HelloWorld( ) As String ' Return "Hello World" 'End Function End Class End Namespace
Example 11-4. Quick web service .asmx file (.cs)
<%@ WebService Language="c#" Codebehind="QuickAndDirtyWS1_CS.asmx.cs" Class="CSWebServices.QuickAndDirtyWS1_CS" %>
Example 11-5. Quick web service code-behind (.cs)
using System; using System.ComponentModel; using System.Web.Services; namespace CSWEbServices { [WebService(Namespace="http://tempuri.org/")] public class CH11QuickWebServiceCS1 : System.Web.Services.WebService { public CH11QuickWebServiceCS1( ) { //CODEGEN: This call is required by the ASP.NET Web Services Designer InitializeComponent( ); } // WEB SERVICE EXAMPLE // The HelloWorld( ) example service returns the string Hello World // To build, uncomment the following lines then save and build the project // To test this web service, press F5 // [WebMethod] // public string HelloWorld( ) // { // return "Hello World"; // } } }
Example 11-6. Code-behind with method for obtaining a list of books (.vb)
Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name: CH11QuickWebServiceVB2.asmx.vb ' ' Description: This class provides the code-behind for ' CH11QuickWebServiceVB2.asmx ' '***************************************************************************** Imports Microsoft.VisualBasic Imports System Imports System.Configuration Imports System.Data Imports System.Data.OleDb Imports System.Web.Services Namespace VBWebServices <WebService(Namespace:="http://www.dominiondigital.com/")> _ Public Class CH11QuickWebServiceVB2 Inherits System.Web.Services.WebService '************************************************************************* ' ' ROUTINE: getBooklist ' ' DESCRIPTION: This routine gets the list of books from the database. '-------------------------------------------------------------------------<WebMethod( )> _
Function getBookList(ByVal numberOfBooks As Integer) As DataSet
Dim dbConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim dSet As DataSet
Dim strConnection As String
Dim strSQL As String
Try
'get the connection string from web.config and open a connection
'to the database
strConnection = _
ConfigurationSettings.AppSettings("dbConnectionString")
dbConn = New OleDbConnection(strConnection)
dbConn.Open( )
'build the query string used to get the data from the database
strSQL = "SELECT Top " & numberOfBooks.ToString( ) & " " & _
"Title, ISBN, Publisher " & _
"FROM Book " & _
"ORDER BY Title"
'create a new dataset and fill it with the book data
dSet = New DataSet
da = New OleDbDataAdapter(strSQL, dbConn)
da.Fill(dSet)
'return the list of books
Return (dSet)
Finally
'clean up
If (Not IsNothing(dbConn)) Then
dbConn.Close( )
End If
End Try
End Function 'getBookList
End Class 'CH11QuickWebServiceVB2 End Namespace
Example 11-7. Code-behind with method for obtaining a list of books (.cs)
//---------------------------------------------------------------------------- // // Module Name: CH11QuickWebServiceCS2.aspx.cs // // Description: This module provides the code behind for the // CH11QuickWebServiceCS2.aspx page // //**************************************************************************** using System; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.OleDb; using System.Web; using System.Web.Services; namespace CSWebServices { [WebService(Namespace="http://www.dominiondigital.com/")] public class CH11QuickWebServiceCS2 : System.Web.Services.WebService { //************************************************************************ // // ROUTINE: getBookList // // DESCRIPTION: This routine gets the list of books from the database. //------------------------------------------------------------------------[WebMethod] public DataSet getBookList(int numberOfBooks)
{
OleDbConnection dbConn = null;
OleDbDataAdapter da = null;
DataSet dSet = null;
String strConnection = null;
String strSQL = null;
try
{
// get the connection string from web.config and open a connection
// to the database
strConnection =
ConfigurationSettings.AppSettings["dbConnectionString"];
dbConn = new OleDbConnection(strConnection);
dbConn.Open( );
//build the query string used to get the data from the database
strSQL = "SELECT Top " + numberOfBooks.ToString( ) + " " +
"Title, ISBN, Publisher " +
"FROM Book " +
"ORDER BY Title";
// create a new dataset and fill it with the book data
dSet = new DataSet( );
da = new OleDbDataAdapter(strSQL, dbConn);
da.Fill(dSet);
//return the list of books
return (dSet);
} // try
finally
{
// cleanup
if (dbConn != null)
{
dbConn.Close( );
}
} // finally
} // getBookList
} // CH11QuickWebServiceCS2 }