Click here to Skip to main content
15,867,453 members
Articles / Web Development / IIS
Article

Your first C# Web Service

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

Introduction

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.

C#
namespace MyService
{
    ...
    /// <summary>
    ///    Summary description for WebService1.
    /// </summary>
    [WebService(Namespace="http://codeproject.com/webservices/",
	            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
            InitializeComponent();
        }

        ...
        
        [WebMethod]
        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 http://tempuri.org. 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:

C#
[WebService(Namespace="http://codeproject.com/webservices/",
            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:

C#
\WebServices
\WebServices\bin
\WebServices\WebService1.asmx
...

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:

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

C#
[WebMethod]
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:

C#
[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:

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

C#
[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.

Conclusion

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.

License

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


Written By
Founder CodeProject
Canada Canada
Chris Maunder is the co-founder of CodeProject and ContentLab.com, and has been a prominent figure in the software development community for nearly 30 years. Hailing from Australia, Chris has a background in Mathematics, Astrophysics, Environmental Engineering and Defence Research. His programming endeavours span everything from FORTRAN on Super Computers, C++/MFC on Windows, through to to high-load .NET web applications and Python AI applications on everything from macOS to a Raspberry Pi. Chris is a full-stack developer who is as comfortable with SQL as he is with CSS.

In the late 1990s, he and his business partner David Cunningham recognized the need for a platform that would facilitate knowledge-sharing among developers, leading to the establishment of CodeProject.com in 1999. Chris's expertise in programming and his passion for fostering a collaborative environment have played a pivotal role in the success of CodeProject.com. Over the years, the website has grown into a vibrant community where programmers worldwide can connect, exchange ideas, and find solutions to coding challenges. Chris is a prolific contributor to the developer community through his articles and tutorials, and his latest passion project, CodeProject.AI.

In addition to his work with CodeProject.com, Chris co-founded ContentLab and DeveloperMedia, two projects focussed on helping companies make their Software Projects a success. Chris's roles included Product Development, Content Creation, Client Satisfaction and Systems Automation.

Comments and Discussions

 
GeneralRe: Test your web service Pin
Troy Russell24-May-09 8:07
Troy Russell24-May-09 8:07 
Questionchanging the web service Pin
qin__231-Aug-08 5:24
qin__231-Aug-08 5:24 
Questionhow to check web service connected successfully or not in c# Pin
lucluv1-Jul-08 21:28
lucluv1-Jul-08 21:28 
AnswerRe: how to check web service connected successfully or not in c# Pin
#realJSOP27-Aug-08 4:48
mve#realJSOP27-Aug-08 4:48 
Generalweb service Pin
anusatya7-Mar-08 23:21
anusatya7-Mar-08 23:21 
GeneralProblem with the classes HttpWebRequest and HttpWebResponse sous C# Pin
zouzoulikou14-Aug-07 4:39
zouzoulikou14-Aug-07 4:39 
GeneralWant to use xml web service from another website database Pin
Abhisriv2-Aug-07 0:32
Abhisriv2-Aug-07 0:32 
GeneralUse SOAP protocol to access Internet Database Server [modified] Pin
nguyenthanhtungtinbk6-Jul-07 12:13
nguyenthanhtungtinbk6-Jul-07 12:13 
This stuff I've done for more than 2 years ago, just want to share to beginners who are getting to know why webservice would be very useful:
http://www.codeproject.com/cs/webservices/webservice_tungDbProxy.asp[^]

Cheers,
Nguyen Thanh Tung
Questionhow to call this web service from C# Pin
anhpqvn7-Jun-07 22:49
anhpqvn7-Jun-07 22:49 
GeneralConfiguration Error in web.config Authentication Mode Pin
Stinger3165-Jun-07 1:17
Stinger3165-Jun-07 1:17 
Generalhelp me Pin
kooosay26-Apr-07 9:44
kooosay26-Apr-07 9:44 
Generalproblems with null parameters Pin
ifms22-Apr-07 22:35
ifms22-Apr-07 22:35 
GeneralRe: problems with null parameters Pin
BloodBaz11-Aug-09 4:03
BloodBaz11-Aug-09 4:03 
GeneralUse external cryptography Pin
Bandoleiro13-Feb-07 7:53
Bandoleiro13-Feb-07 7:53 
GeneralThanks! Pin
Coder_200729-Jan-07 9:59
Coder_200729-Jan-07 9:59 
GeneralRe: Thanks! Pin
Troy Russell24-May-09 7:35
Troy Russell24-May-09 7:35 
GeneralRe: Thanks! Pin
Troy Russell24-May-09 7:50
Troy Russell24-May-09 7:50 
Generalproblem with webservices:( Pin
beganovic_swe23-Jan-07 8:36
beganovic_swe23-Jan-07 8:36 
GeneralRe: problem with webservices:( Pin
vnnsmile8-Feb-07 16:39
vnnsmile8-Feb-07 16:39 
QuestionWhat can I do? Pin
jinda_tra@hotmail.com9-Nov-06 17:51
jinda_tra@hotmail.com9-Nov-06 17:51 
GeneralObject instead of XML Pin
irishdunn2-Nov-06 10:23
irishdunn2-Nov-06 10:23 
GeneralUsing a struct passed from a C# web service at the client Pin
jvink2-Nov-06 0:18
jvink2-Nov-06 0:18 
GeneralPlease help Pin
ioanavic27-Oct-06 11:05
ioanavic27-Oct-06 11:05 
GeneralDeployment Pin
Neophyte3025-Oct-06 4:01
Neophyte3025-Oct-06 4:01 
GeneralRe: Deployment Pin
choudharyn22-Jun-07 8:36
choudharyn22-Jun-07 8:36 

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.