Saying Hello to Web Services

9/27/2010 5:38:59 PM
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:

  1. Choose File => New => Web Site.

    The New Web Site window appears.

  2. Click the ASP.NET Web Service template.

  3. Type a name for your Web service.

    Give your Web service a meaningful name.

  4. 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.


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:

  1. 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."

  2. 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.

Figure 1. ASP.NET generates a page to test the Web service's methods.

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.

Figure 2. A Web service includes an entry point and a class.

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:

  1. Right-click the .asmx file in Solution Explorer.

  2. Choose Rename from the shortcut menu.

  3. 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.

  4. 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.

  5. Open the class file and change the class' name from Service to its new name, such as HelloWebService.

  6. 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" %>


    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.

  7. 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 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.


The default namespace 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.

Figure 3. Change the name of the Web service to make it more descriptive.

To change the namespace and add a description to the Web service, follow these steps:

  1. Open the class file used by your service.

    The class file is in the App_Code folder.

  2. 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="", 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.

  3. 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.

Figure 4. Use the Description property to add descriptions to your Web service and methods.

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

Figure 5. Use the WebMethod attribute to make a public method accessible via a Web service.

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:


  • 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. 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:

<add name="HttpGet"/>

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:


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.

Figure 6. The Web service returns an XML document.

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:

  1. Click the Web service in Solution Explorer.

    Press Ctrl+Alt+L to open Solution Explorer if it's closed.

  2. Choose Website => Add New Item.

    The Add New Item window appears.

  3. Click the HTML Page icon.

  4. Type a name for the HTML page and then click Add.

    The HTML page appears in the Code Editor.

  5. Type the following HTML to create a form:

    <form method="POST" action='http://<servername>/

    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.

  6. Drag and drop input elements for text from the toolbox onto the HTML page.

  7. Drag and drop a Submit button (note that the button type is Submit, even though the caption reads button).


    Make sure that the elements appear between the form tags.

  8. 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"

    Enter Your Name:
    <input id="Text1" type="text" name="name"/>
    <input id="Button1" type="submit" value="button" />

  9. 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.

  10. Type the parameter values in the page, as shown in Figure 7.

  11. Click button.

    Figure 7. Type the parameter values in to the test page.

    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 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.

Figure 8. ASP.NET generates sample SOAP messages.

Here's how to create a test for SOAP:

  1. Add a new HTML page to your project.

  2. Add a script tag to the page between the head tags, as shown in the following:

    <script type="text\jscript">

  3. Create a new object to hold an XML document:

    var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");

  4. Create a new object to communicate with a Web server:

    var xmlHTTP = new ActiveXObject("Msxml2.XMLHTTP");

  5. 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=\"
    XMLSchema-instance\" " ;
    soapXml += "xmlns:xsd=\"
    XMLSchema\" " ;
    soapXml += "xmlns:soap12=\
    soapXml += "<soap12:Body>" ;
    soapXml += "<HelloWorld xmlns=\
    "\">" ;
    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=""
    <HelloWorld xmlns=

  6. 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);
    "application/soap+xml; charset=utf-8" );
    xmlHTTP.setRequestHeader("Content-Length", xmlDoc.

    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

  7. Create a function that outputs the SOAP request and response to the Web page:

    function writeResponses()
    SoapRequest.innerText =" xmlDoc.xml;
    SoapResponse.innerText =" xmlHTTP.responseText;

  8. Create a function that calls all three functions:

    function getSoap(name)

  9. Add an HTML form that wires everything up:

    <p>Enter name:<input id="inputName">
    <p><input type="button" id="btn"" value="Enter"
    <div id="SoapRequest"></div>
    <div id="SoapResponse"></div>

  10. Display the page in the browser.

    Figure 9 shows an example.

This script is modified from the script at

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.

Figure 9. Use a Web page to test your SOAP requests and responses.

Most View
Is Blue The Color? (Part 2)
Fujifilm X-E1 - A Retro Camera That Inspires (Part 1)
The Sony Xperia SP - The Impressive Mid-Range Android Smartphone
Windows 7 : Managing Print Jobs (part 3) - Creating XPS Documents
EVGA GeForce GTX 650 1GB - Severely Cut Down From GTX 660 Ti
30 Something CD Players Group Test (Part 4) - Quad Elite CDS
Chillblast Fusion Blaze - Perfectly Overclocked System
Slim, Light And Mighty Ultrabooks Supertest (Part 3) : Lenovo IdeaPad U300s, HP Envy 14 Spectre, Lenovo U300s
Blackberry Q10 - An Ultimate Messaging Machine For Socializing, Sharing And Working (Part 2)
Western Digital Sentinel DX4000 NAS Review (Part 4)
Top 10
Sharepoint 2013 : Farm Management - Disable a Timer Job,Start a Timer Job, Set the Schedule for a Timer Job
Sharepoint 2013 : Farm Management - Display Available Timer Jobs on the Farm, Get a Specific Timer Job, Enable a Timer Job
Sharepoint 2013 : Farm Management - Review Workflow Configuration Settings,Modify Workflow Configuration Settings
Sharepoint 2013 : Farm Management - Review SharePoint Designer Settings, Configure SharePoint Designer Settings
Sharepoint 2013 : Farm Management - Remove a Managed Path, Merge Log Files, End the Current Log File
SQL Server 2012 : Policy Based Management - Evaluating Policies
SQL Server 2012 : Defining Policies (part 3) - Creating Policies
SQL Server 2012 : Defining Policies (part 2) - Conditions
SQL Server 2012 : Defining Policies (part 1) - Management Facets
Microsoft Exchange Server 2010 : Configuring Anti-Spam and Message Filtering Options (part 4) - Preventing Internal Servers from Being Filtered