Home Page
Looking for a better way to learn C# and ASP.NET? Take a look at the source code for a working program and see how the pieces all fit together.
- - -
Click here to read more and take a free video tour. This is a great deal, act now and learn tricks you can use to improve your own programs.

Category: Advanced ASP.NET

Click here to download the source code for this lesson.

In this lesson I am going to discuss how to create an ASP.NET C# web service that runs a database query and returns a list of data.  The web service created in this lesson, queries data from a database table named “customer”.  In the next lesson, I will discuss how to call or consume the web service created in this exercise and display the customer data on a web form using a GridView server control, so please read that lesson when you finish with this one.  I split these two apart in order to make it easier to follow along since there are several steps involved.

Before I begin with the lesson, let me just cover some background information about web services and what they are used for.  A web service is a special kind of web site.  It is different from a traditional ASP.NET web site that produces HTML code.  In fact, a web service had no graphical user interface and produces XML.  A web service exposes one or more methods that your application can call remotely.  This is called a remote procedure call.  It basically means that you can have web service A sitting on a web server and another ASP.NET web application B sitting on a different server, and application B can call or communicate with web service A, even though they are in separate physical machines.  It turns out that this feature of web services makes them very useful for many reasons: scalability, ensapsulation of logic, and security.

Web services are implemented internally using an Internet protocol called SOAP, which passes XML messages back and forth between a web service client application and a web service.  The SOAP protocol is an Internet standard which makes web services interoperable or cross-platform (e.g. Java can communicate with .NET and .NET can communicate with Java); the two can integrate with each other seamlessly by using web services.  You don’t have to understand how SOAP works in order to program an ASP.NET web service, and a lot of programmers probably don’t.  That is one of the strengths of the .NET framework and the Visual Studio IDE.  In this lesson you will learn how quickly you can create web services and become productive with them.

Alright, let’s get started.  To create an ASP.NET web service with Visual Web Developer, click on File->New Web Site, then choose ASP.NET Web Service from the templates list.  Type in the name of your web service project at the bottom of the screen and click OK.  In this lesson, I called my project Lab17_csharpuniversity_webservice.  The IDE will create a template project with one default web service called Service.asmx.  Notice the file extension of .asmx, which is different from what we are used to seeing with traditional ASP.NET web form (.aspx).

The name Service.asmx is too generic, so it’s a good idea to create one that has a more meaningful name for your application.  Right click on the project name in the Solution Explorer and choose Add New Item.  Choose Web Service from the templates list and type in the name for the new service at the bottom.  I named my new service file CustomerData.asmx.  Make sure that Place code in separate file is checked.  Click OK and the IDE will create the new file.  You will notice that the IDE automatically generated a file named CustomerData.cs in the App_Code folder.  That is the code-behind file and contains all the programming for the web service.  If you open the file CustomerData.asmx you will see that it’s just a one liner that references the CustomerData.cs file, where the code actually is.  Right click on the CustomerData.asmx file and choose Set as start page.  Then delete the files Service.asmx and Service.cs since we won’t need those anymore.

What we are left with after all of this are the files CustomerData.asmx and CustomerData.cs.  Now it’s time to add some code into our web service.  Open the file CustomerData.cs and add the following two lines of code at the top:

using System.Data;
using System.Data.SqlClient;

Next, we are going to replace the existing method named HelloWorld (sorry hello world lovers).  Highlight the HelloWorld method and replace it with the following code:

    public string getCustomers()
        SqlDataAdapter dbadapter = null;
        DataSet returnDS = new DataSet();

        using (SqlConnection dbconn = new SqlConnection(
            + "Database=csharpuniversity;"
            + "User ID=sa;"
            + "Password=Sqlserverpass$123;"
            + "Trusted_Connection=False;"))
            SqlCommand cmd = new SqlCommand();
            string sqlQuery = "select * from customer";

            cmd.CommandText = sqlQuery;
            cmd.Connection = dbconn;
            dbadapter = new SqlDataAdapter(cmd);


        return returnDS.GetXml();

Let’s talk about this method.  First you will notice that I had to put [WebMethod] right above the method declaration.  This lets the ASP.NET IDE know that you intend to expose this method so that it can be called by application clients of this web service.  If you forget to put that, your method won’t be accessible to applications calling this web service CustomerData.asmx.

Next, the method itself is pretty basic.  It executes a query against a SQL Server database and returns all of the data in the source table “customer”.  A trick that I am using here is to return the database data as an XML string.  The ADO.NET DataSet class has a method named GetXml that makes this quite easy.  The benefits of having my web service method getCustomers return back an XML list of data are that it is: easy because it doesn’t require much coding (i.e. I don’t have to transform the data into any typed object) and that it makes the web service interoperable with Java and other non-.net languages that can interpret XML.  This technique of returning XML data from a web service method can be used in any scenario where you need to return a list of data to client applications.

As a final part of this lesson, we need to unit test the web service and make sure that it works correctly.  Make sure that your database is up and running before you proceed.  To test an ASP.NET web service, all you have to do is click the Play button just like you would with a traditional ASP.NET web site project.  Turn on debugging if you get prompted.  Visual Web Developer will launch your web browser with a URL that looks similar to: http://localhost:1775/Lab17_csharpuniversity_webservice/CustomerData.asmx.

Notice that the .asmx file is the one that represents your web service.  A web page will come up that lists all of the methods in your web service class that were marked with the [WebMethod] directive.  In my example it is the method getCustomers.  If you click on getCustomers, it will take you to another web page where you can actually test the method.  The web page that comes up will have a bunch of information about the SOAP request and response.  You don’t need to be concerned about all of that.  You can click on the Invoke button, and that will execute your method.  Then another web page will open with the results of the operation.  If any data was returned, it will be displayed in XML format.  In my case I get a list of XML nodes that look like:

<email_address>[email protected]</email_address>

Each node represents a unique customer in my database.  This XML string is what will be received by client applications that call this web service.  Notice that the .NET framework and IIS automatically create this set of test web pages that we just used in order to allow developers to test their web services from a web browser.  This is very helpful and can even help in production debugging where I have personally used this feature to diagnose web service problems.  By default IIS, only allows access to this unit test application if you are running it from the same machine where the web service is deployed.

One more thing I want to cover before closing out this lesson, is to discuss the XML Namespace of the web service.  Every web service has an XML Namespace name that is used by the internal SOAP processors to uniquely identify the service.  Think of the XML Namespace as like the identity fingerprint for the service.  It ensures that your web service contains a unique branding that logically differentiates it from other web services.  You can set the Namespace for your web service at the top of the code-behind file.  You can use a common Namespace for your organization as I did in my file:


[WebService(Namespace = "/webservices")]

Click here to watch a video where I show you how to perform all of the steps mentioned above to create an ASP.NET C# web service.

What do you intend to use a web service for?

Did you like this lesson? Enter your Email

You get notified anytime a new article is posted and you can unsubscribe at anytime.

No Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment