Web
services make extensive use of Web-based technologies, such as HTTP and
XML. Thankfully, you don't need to dig into how Web services use these
technologies because Visual Studio and ASP.NET take care of all that
for you.
To create a new Web service, follow these steps:
Choose File => New => Web Site.
The New Web Site window appears.
Click the ASP.NET Web Service template.
Type a name for your Web service.
Give your Web service a meaningful name.
|
|
Click OK.
Visual Studio creates the Web service project.
The Web service
created by Visual Studio is fully functional. To run the Web service,
press Ctrl+F5. Visual Studio launches the service in your Web browser.
NOTE
Web services don't have user interfaces. ASP.NET uses a template to generate the service.asmx page. The page lists a single method, HelloWorld, created by Visual Studio.
To test the HelloWorld method, do the following:
Click the HelloWorld hyperlink on the service.asmx page.
A test page appears, as shown in Figure 1.
The
page includes a button to invoke the test method. It also shows the
sample Simple Object Access Protocol (SOAP) headers that ASP.NET uses
to communicate with the Web service using SOAP. You don't need to know
SOAP to perform basic tasks with Web services because Visual Studio and
ASP.NET take care of all that for you. However, a knowledge of SOAP is
very helpful when you want to perform advanced tasks and need to debug
your application. SOAP is explained in more detail in the upcoming
section "Testing Web services."
Click the Invoke button.
An XML file appears with the value Hello World in a single string node.
To stop testing the Web
service, right-click the ASP.NET Development Server icon in the
Notification and choose Stop from the contextual menu. The Web service
becomes unavailable at this point.
1. Understanding ASP.NET Web services
A Web service project
comprises two main components: an entry point to access the service and
a class that contains the code for the Web service. Because Web
services don't have user interfaces like Web sites, Web services in
ASP.NET are accessed via an .asmx page, which serves as the entry point to the Web service. An .asmx page has a WebService
processing directive at the top of the page that defines the
programming language of the Web service, the code-behind file, and the
class name that provides the Web service's functionality. The features
of a Web service are implemented in a class. The class uses attributes
to identify which methods are publicly accessible via the Web service.
Using attributes allows you to use private methods in your class.
Although most Web services aren't accessed via .asmx pages, ASP.NET Web sites are typically accessed via .aspx pages.
|
|
Figure 2 shows an example of a simple HelloWorld Web service created with Visual Studio.
Visual Studio
automatically wires up the Web service's class with the attributes that
it needs to function as a Web service. The class that Visual Studio
creates for the Web service uses two attributes:
WebService: A Web service has one WebService attribute that identifies the Web service's namespace. The attribute can also include a description.
WebMethod: Each method that's accessible from the Web service must have the WebMethod attribute above it.
To change the name of the service and the class created by Visual Studio, follow these steps:
Right-click the .asmx file in Solution Explorer.
Choose Rename from the shortcut menu.
Type a new name for the .asmx file, such as HelloWebService.asmx.
The name you use for the .asmx file is the name you use to access the Web service via its URL.
|
|
Repeat Steps 1 through 3 to rename the Service.vb or Service.cs class created by Visual Studio.
The class is located in the App_Code folder.
The file extension depends on whether you're using Visual Basic (.vb) or C# (.cs) as the programming language.
Open the class file and change the class' name from Service to its new name, such as HelloWebService.
Open the .asmx file and change the WebService processing directive so that it points to the new class file and name, as shown in the following code:
<%@ WebService Language="C#" CodeBehind="~/App_Code/HelloWebService.cs"
Class="HelloWebService" %>
NOTE
An .asmx file can
point to more than just a class file. It can also point to a
precompiled assembly, or you can include your code inside the .asmx file.
Press Ctrl+F5 to run the Web service.
Notice that the Web service's name and URL are updated, as shown in Figure 3.
Each Web service must have a
unique namespace. The namespace qualifies the Web service's methods so
that each method is unique. Visual Studio automatically assigns the
namespace http://tempuri.org/
to Web services. You should change the namespace. The namespace doesn't
have to point to an actual working URL. Rather, it should be unique.
However, some Web services do use a URL that points to a Web site with
useful information about the Web service.
NOTE
The default namespace http://tempuri.org/ is pronounced TEMP-you-are-eye, which is short for temporary URI. A URI — Uniform Resource Identifier — is used to provide a name or location for a resource.
To change the namespace and add a description to the Web service, follow these steps:
Open the class file used by your service.
The class file is in the App_Code folder.
Type a new namespace in place of the default namespace and add a description for the Web service, as shown in the following:
[WebService(Namespace="http://mycompany.com/webservices", Description= "A
web service that returns a Hello World message")]
The WebMethod attribute supports the Description property. Use it to add a description to the methods exposed by your Web service.
Press Ctrl+F5 to run the Web service.
The Web service's description appears on the ASP.NET-generated page, as shown in Figure 4. Notice also that a description for the HelloWorld method appears.
2. Adding a method
The methods that you add to
your Web service class aren't automatically accessible via your Web
service. You must explicitly mark them as Web service methods.
You mark Web service methods with a WebMethod attribute. Figure 5 shows a code sample with a single public method that uses two private methods. The publicWebMethod attribute. Note that the private methods aren't accessible. method is marked with the
3. Testing Web services
Short of building a full-blown
application, you have several ways to test your Web services. The
easiest way to test your Web services is to press F5 while in Visual
Studio. You can also access your Web services via its URL or by using
an HTTP form. In most cases, you communicate with Web services via HTTP
(the communication protocol of the Internet).
Whichever method you choose, you must be aware of your three communication choices when working with Web services:
GET: Uses
HTTP with an encoded URL to call the Web service. This method is very
much like the Representative State Transfer (REST) technique used by
many public Web services — it has the advantage of being incredibly
easy to use and test. The basic syntax for accessing a Web service with
GET is to use a URL like the following:
http://<servername>/<projectname>/service.asmx/
methodname?parameter1=value¶meter2=value
POST: Uses HTTP to pass the method's parameters without displaying them in the URL. The POST approach is more secure.
SOAP: Uses an XML dialect called SOAP to enclose the request to and response from the Web service. SOAP is often used in conjunction with HTTP, although it isn't required. SOAP is the standard for Web services message encapsulation.
The testing services provided by ASP.NET use POST by default. The following section shows you how to enable testing with GET. ASP.NET doesn't provide a facility for testing SOAP messages.
6.2.3.1. Sending a GET request
To see a GET request at
work, you must modify the default code provided with the Web service.
The following code shows the modified version:
<WebMethod()> _
Public Function HelloWorld(ByVal name As String) _
As String
' Supply a default value if the value is blank.
If name.Length = 0 Then
name = "World"
End If
' Return a hello string.
Return "Hello " & name
End Function
Visual Studio doesn't initially provide HTTP GET, so you need to enable the GET protocol in your project's web.config file. To add the protocol, paste the following code between the opening and closing <system.web> tags in web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
</protocols>
</webServices>
A GET request passes the Web services parameters with the URL. For example, the following URL calls the HelloWorld method on the HelloWebService and passes the value John to the name parameter:
http://localhost:49166/WebService/HelloWebService.asmx/
HelloWorld?name=John
The port that your
ASP.NET Development Server uses will vary from these because Visual
Studio generates a random number for each project. To see the port
number for your setup, hover the mouse cursor over the ASP.NET
Development Server icon in the Notification area and use that port
number in the GET URL you create. The Web service returns an XML
document with the value Hello John, as shown in Figure 6.
Passing in parameters at the end of a URL is encoding. Any time you see a URL with parameters appended, your browser sends an HTTP GET request to the Web server. GET requests are considered more risky than POST requests because the parameter values are in plain sight. The alternative is to use an HTTP POST request, which sends the parameter values in the message body.
3.2. Sending a POST request
You can use an HTML form to test your Web service by using a POST request. With a POST request, the Web service's parameters aren't visible in the URL.
To test a Web service with an HTTP form, follow these steps:
Click the Web service in Solution Explorer.
Press Ctrl+Alt+L to open Solution Explorer if it's closed.
Choose Website => Add New Item.
The Add New Item window appears.
Click the HTML Page icon.
Type a name for the HTML page and then click Add.
The HTML page appears in the Code Editor.
Type the following HTML to create a form:
<form method="POST" action='http://<servername>/
<projectname>/HelloWebService.asmx/HelloWorld'>
</form>
The action
attribute specifies where the form should post. Type the URL of your
Web service. Append a forward slash and the name of the method to
execute. In the preceding example, the form executes the HelloWorld method on the Web service.
Drag and drop input elements for text from the toolbox onto the HTML page.
Drag and drop a Submit button (note that the button type is Submit, even though the caption reads button).
NOTE
Make sure that the elements appear between the form tags.
Set the name attribute for your input elements to the parameter for your method.
For example, the following HTML form posts to the HelloWorld method of the HelloWebService (note that the action attribute appears on a single line in your code):
<form method="POST"
action='http://localhost:49166/WebService/
HelloWebService.asmx/HelloWorld'>
Enter Your Name:
<input id="Text1" type="text" name="name"/>
<input id="Button1" type="submit" value="button" />
</form>
Press Ctrl+F5 to run your Web page.
The page appears.
Make
sure that you have the HTML page open when you press Ctrl+F5 or set the
HTML page as the startup page for the site. Otherwise, you'll see the
Web service test page open, rather than the HTML page. If you make a
mistake, simply select the HTML page and press Ctrl+F5.
Type the parameter values in the page, as shown in Figure 7.
Click button.
When you click the Submit button, the HTML page sends the parameters in the form parameter=value to the Web service method. Using the example in Figure 7, the browser submits name=John to the Web service.
The Web service responds with an XML document containing the value Hello John, as shown in Figure 6.
3.3. Testing with SOAP
You might also want to test
the SOAP messages generated by your Web service. The test page
generated for your Web service shows a sample SOAP message that ASP.NET
generates, as shown in Figure 8.
Because SOAP messages
are XML-based, you can use standard Web technologies to test the
messages. You'll find an excellent SOAP tutorial at www.w3schools.com/soap/default.asp.
The following example uses JScript and Microsoft eXtensible Markup
Language (MSXML) Core Services to submit a SOAP request and display the
response. MSXML is the Microsoft XML parser. You use it to process the XML you send and receive. JScript
is a client-side scripting language that you use to display values on
the Web page. The following example shows you how to use MSXML and
JScript to test SOAP messages without assuming that you have any
knowledge of these technologies.
Here's how to create a test for SOAP:
Add a new HTML page to your project.
Add a script tag to the page between the head tags, as shown in the following:
<head>
<script type="text\jscript">
</script>
</head>
Create a new object to hold an XML document:
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
Create a new object to communicate with a Web server:
var xmlHTTP = new ActiveXObject("Msxml2.XMLHTTP");
Create a new function that creates the SOAP message and loads it into the XML document that you create in Step 3:
function createXmlDoc(name)
{
var soapXml" = "<?xml version=\"1.0\" ?>" ;
soapXml += "<soap12:Envelope ";
soapXml += "xmlns:xsi=\"http://www.w3.org/2001/
XMLSchema-instance\" " ;
soapXml += "xmlns:xsd=\"http://www.w3.org/2001/
XMLSchema\" " ;
soapXml += "xmlns:soap12=\
"http://www.w3.org/2003/05/soap-envelope\">";
soapXml += "<soap12:Body>" ;
soapXml += "<HelloWorld xmlns=\
"http://mycompany.com/webservices\">" ;
soapXml = soapXml + "<name>" + name.value" +
"</name>" ;
soapXml += "</HelloWorld>";
soapXml += "</soap12:Body></soap12:Envelope>"
xmlDoc.loadXML(soapXml) ;
}
You can find an example of
the SOAP request on the Web service's test page. Be sure to pass any
parameter values to the request. For example, here's the SOAP request
generated by ASP.NET for the Web service shown in Figure 5:
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap12="http://www.w3.org/2003/05/
soap-envelope">
<soap12:Body>
<HelloWorld xmlns=
"http://mycompany.com/webservices">
<name>string</name>
</HelloWorld>
</soap12:Body>
</soap12:Envelope>
Create a function that sends the SOAP request to the Web server.
The following is an example of how to create a function:
function sendXml()
{
xmlHTTP.Open ( "Post", "http://localhost:4251/
HelloWebService/HelloWebService.asmx", false);
xmlHTTP.setRequestHeader("Content-Type",
"application/soap+xml; charset=utf-8" );
xmlHTTP.setRequestHeader("Content-Length", xmlDoc.
xml.length);
xmlHTTP.Send(xmlDoc.xml);
}
The sendXML function uses the XMLHTTP
object to send the SOAP request to the Web service. You can find the
header information for the request on the Web service's test page.
Here's the SOAP request generated for the Web service shown in Figure 5:
POST /HelloWebService/HelloWebService.
asmx HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
Create a function that outputs the SOAP request and response to the Web page:
function writeResponses()
{
SoapRequest.innerText =" xmlDoc.xml;
SoapResponse.innerText =" xmlHTTP.responseText;
}
Create a function that calls all three functions:
function getSoap(name)
{
createXmlDoc(name);
sendXml();
writeResponses();
}
Add an HTML form that wires everything up:
<form>
<p>Enter name:<input id="inputName">
</input></p>
<p><input type="button" id="btn"" value="Enter"
onclick="getSoap(inputName)"></input>
</p>
<p>Request:</p>
<div id="SoapRequest"></div>
<p>Response:</p>
<div id="SoapResponse"></div>
</form>
Display the page in the browser.
Figure 9 shows an example.
This script is modified from the script at
www.codeproject.com/webservices/aspwebsvr.asp
You can also use the testing
facilities in Visual Studio Team System (VSTS) to create a Web test to
test your Web services. See the topic "How to: Create a Web Service
Test," in the Visual Studio documentation, for more information.