Click here to Skip to main content
15,034,644 members
Articles / Web Development / IIS
Posted 12 Dec 2000


536 bookmarked

Your first C# Web Service

Rate me:
Please Sign up or sign in to vote.
4.61/5 (217 votes)
5 Jun 2002CPOL
An introduction to writing your first WebService


Creating your first web service is incredibly easy. In fact, by using the wizards in Visual Studio. NET you can have your first service up and running in minutes with no coding.

For this example I have created a service called MyService in the /WebServices directory on my local machine. The files will be created in the /WebServices/MyService directory.

Image 1

A new namespace will be defined called MyService, and within this namespace will be a set of classes that define your Web Service. By default the following classes will be created:

Global (in global.asax) Derived from HttpApplication. This file is the ASP.NET equivalent of a standard ASP global.asa file.
WebService1 (in WebService1.cs) Derived from System.Web.Services.WebService. This is your WebService class that allows you to expose methods that can be called as WebServices.

There are also a number of files created:

AssemblyInfo.cs Contains version and configuration information for your assembly.
web.config Defines how your application will run (debug options, the use of cookies etc).
MyService.disco Discovery information for your service.
WebService1.asmx Your WebService URL. Navigate to this file in a browser and you will get back a user-friendly page showing the methods available, the parameters required and the return values. Forms are even provided allowing you to test the services through the web page.
bin\MyService.dll The actual WebService component. This is created when you build the service.

The class for your service that is created by default is called (in this case) WebService1, and is within the MyService namespace. The code is partially shown below.

namespace MyService
    /// <summary>
    ///    Summary description for WebService1.
    /// </summary>
	            Description="This is a demonstration WebService.")]
    public class WebService1 : System.Web.Services.WebService
        public WebService1()
            //CODEGEN: This call is required by the ASP+ Web Services Designer

        public string HelloWorld()
            return "Hello World";

A default method HelloWorld is generated and commented out. Simply uncomment and build the project. Hey Presto, you have a walking talking WebService. 

A WebService should be associated with a namespace. Your Wizard-generated service will have the name space If you compile and run the service as-is you'll get a long involved message indicating you should choose a new namespace, so we add the namespace, and the WebService description as follows:

            Description="This is a demonstration WebService.")]
public class WebService1 : System.Web.Services.WebService

To test the service you can right click on WebService1.asmx in the Solution Explorer in Visual Studio and choose "View in Browser". The test page is shown below,

Image 2

When invoked this returns the following:

Image 3

Getting the demo application to run

If you downloaded the source code with this article then you will need to create a directory 'WebServices' in your web site's root directory and extract the downloaded zip into there. You should then have:


Navigating to http://localhost/WebServices/WebService1.asmx won't show you the WebService because you need to ensure that the webservice's assembly is in the application's /bin directory. You will also find that you can't load up the solution file MyService.sln. To kill two birds with one stone you will need to fire up the IIS management console, open your website's entry, right click on the WebServices folder and click Properties. Click the 'Create' button to create a new application the press OK. The /WebServices directory is now an application and so the .NET framework will load the WebService assembly from the /WebServices/bin directory, and you will be able to load and build the MyService.sln solution.

Image 4

Extending the example

So we have a WebService. Not particularly exciting, but then again we haven't exactly taxed ourselves getting here. To make things slightly more interesting we'll define a method that returns an array of custom structures.

Within the MyService namespace we'll define a structure called ClientData:

public struct ClientData
    public String Name;
    public int    ID;

and then define a new method GetClientData. Note the use of the WebMethod attribute in front of the method. This specifies that the method is accessible as a WebService method.

public ClientData[] GetClientData(int Number)
    ClientData [] Clients = null;

    if (Number > 0 && Number <= 10)
        Clients = new ClientData[Number];
        for (int i = 0; i < Number; i++)
            Clients[i].Name = "Client " + i.ToString();
            Clients[i].ID = i;
    return Clients;

If we compile, then navigate to the the .asmx page then we are presented with a form that allows us to enter a value for the parameter. Entering a non-integer value will cause a type-error, and entering a value not in the range 1-10 will return a null array. If, however, we manage to get the input parameter correct, we'll be presented with the following XML file:

Image 5

It's that easy.

Caching WebServices

Often a WebService will return the same results over multiple calls, so it makes sense to cache the information to speed things up a little. Doing so in ASP.NET is as simple as adding a CacheDuration attribute to your WebMethod:

[WebMethod(CacheDuration = 30)]
public ClientData[] GetClientData(int Number)

The CacheDuration attribute specifies the length of time in seconds that the method should cache the results. Within that time all responses from the WebMethod will be the same.

You can also specify the CacheDuration using a constant member variable in your class:

private const int CacheTime = 30;	// seconds

[WebMethod(CacheDuration = CacheTime)]
public ClientData[] GetClientData(int Number)

Adding Descriptions to your WebMethods

In the default list of WebMethods created when you browse to the .asmx file it's nice to have a description of each method posted. The Description attribute accomplishes this.

[WebMethod(CacheDuration = 30,
 Description="Returns an array of Clients.")]
public ClientData[] GetClientData(int Number)

Your default .asmx page will then look like the following:

Image 6

There are other WebMethod attributes to control buffering, session state and transaction support.

Deploying the WebService

Now that we have a WebService it would be kind of nice to allow others to use it (call me crazy, but...). Publishing your WebService on your server requires that your solution be deployed correctly. On the Build menu of Visual Studio is a "Deploy" option that, when first selected, starts a Wizard that allows you to add a Deployment project to your solution. This creates an installation package that you can run on your server which will create the necessary directories, set the correct parameters and copy over the necessary files.

This doesn't really give you an idea of what, exactly, is happening, so we'll deploy our MyService manually.

Deploying the application is done using the steps in Getting the demo application to run. We need to create a directory for our service (or use an existing directory) for our .asmx file, and we need to have the service's assembly in the application's bin/ directory. Either place the .asmx file in a subdirectory on your website and place the assembly in the /bin folder in your website's root, or place the /bin in the subdirectory containing the .asmx file and mark that directory as an application (see above).

If you choose to create a separate directory and mark it as an application then Within this directory you need to add the following files and directories:

MyService.asmxThis file acts as the URL for your service
MyService.discoThe discovery document for your service
web.configConfiguration file for your service that overrides default web settings (optional).
/binThis directory holds the assembly for your service
/bin/MyService.dllThe actual service asembly.


Writing WebServices is extremely easy. Using the Visual Studio. NET wizards makes writing and deploying these services a point and click affair, but even if you wish to do it by hand then the steps involved are extremely simple.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Chris Maunder
Founder CodeProject
Canada Canada
Chris is the Co-founder, Administrator, Architect, Chief Editor and Shameless Hack who wrote and runs CodeProject. He is also co-founder of Developer Media and ContentLab.IO. He's been programming since the 80's and has been, in various guides, an astrophysicist, bacyard mechanic, mathematician, physicist, breeder of carnivorous plants, hydrologist, geomorphologist, defence intelligence researcher and then, when all that got a bit rough on the nerves, a web developer.

His programming experience includes C/C++, C#, SQL, MFC, ASP.NET, TypeScript and far, far too much FORTRAN. He has worked on PocketPCs, Old mainframes, new Macs, cheap phones, and a CRAY YMP C90 behemoth but finds notebooks take up less desk space.

He is kind to small animals and has a soft spot for cheesecake.

Chris was born and bred in Australia but splits his time between Toronto and Melbourne, depending on the weather. For relaxation he is obsessively into road cycling, physiology, occasionally snowboarding and rock climbing, and wishes he were a storm chaser.

Comments and Discussions

QuestionIs this example still current? Pin
hockeypuck1-Dec-15 10:18
Memberhockeypuck1-Dec-15 10:18 
AnswerRe: Is this example still current? Pin
Chris Maunder1-Dec-15 15:50
cofounderChris Maunder1-Dec-15 15:50 
QuestionFirst time implementing a web services Pin
hauna11-Jun-14 1:25
Memberhauna11-Jun-14 1:25 
AnswerRe: First time implementing a web services Pin
jazygift4-Jul-18 2:36
Memberjazygift4-Jul-18 2:36 
GeneralRe: First time implementing a web services Pin
Richard Deeming5-Jul-18 4:04
mveRichard Deeming5-Jul-18 4:04 
GeneralMy vote of 5 Pin
RicardoAR8821-May-14 4:01
MemberRicardoAR8821-May-14 4:01 
Questionwebservice sample with json Pin
Mehdipirmoradian21-Mar-14 12:39
MemberMehdipirmoradian21-Mar-14 12:39 
AnswerRe: webservice sample with json Pin
Member 132423255-Jun-17 15:22
MemberMember 132423255-Jun-17 15:22 
QuestionHow do I call this service from a Classic ASP page Pin
Member 1039726012-Nov-13 9:05
MemberMember 1039726012-Nov-13 9:05 
GeneralMy vote of 5 Pin
chetankumar s19-Aug-13 20:02
Memberchetankumar s19-Aug-13 20:02 
GeneralMy vote of 5 Pin
darkelflemurian19-Aug-13 9:54
Memberdarkelflemurian19-Aug-13 9:54 
GeneralMy vote of 2 Pin
Member 94605004-Jun-13 9:30
MemberMember 94605004-Jun-13 9:30 
GeneralRe: My vote of 2 Pin
jliveston9-Oct-13 10:56
Memberjliveston9-Oct-13 10:56 
GeneralRe: My vote of 2 Pin
jazygift4-Jul-18 2:37
Memberjazygift4-Jul-18 2:37 
Questionproblem Atl with Webservice Pin
azadehrasadi4-May-13 19:41
Memberazadehrasadi4-May-13 19:41 
GeneralMy vote of 3 Pin
Таньо Тодоров Иванов21-Jan-13 21:56
MemberТаньо Тодоров Иванов21-Jan-13 21:56 
GeneralMy vote of 5 Pin
ekyle12518-Jan-13 5:07
Memberekyle12518-Jan-13 5:07 
GeneralMy vote of 3 Pin
Gaurang Naik14-Jan-13 1:54
MemberGaurang Naik14-Jan-13 1:54 
Questionhow can work webservices in dotnet 4.0 Pin
sriharikodali29-Jun-12 2:06
Membersriharikodali29-Jun-12 2:06 
GeneralMy vote of 5 Pin
Chandrashekar SK25-Jun-12 20:33
MemberChandrashekar SK25-Jun-12 20:33 
GeneralMy vote of 5 Pin
Jesus Carroll7-May-12 12:54
professionalJesus Carroll7-May-12 12:54 
GeneralMy vote of 3 Pin
imed.abid11-Apr-12 3:19
Memberimed.abid11-Apr-12 3:19 
QuestionDisplay array results in an aspx page for testing Pin
xenomatic4-Apr-12 6:33
Memberxenomatic4-Apr-12 6:33 
AnswerRe: Display array results in an aspx page for testing Pin
Chris Maunder4-Apr-12 8:50
cofounderChris Maunder4-Apr-12 8:50 
GeneralRe: Display array results in an aspx page for testing Pin
xenomatic4-Apr-12 9:50
Memberxenomatic4-Apr-12 9:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.