Click here to Skip to main content
Email Password   helpLost your password?

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.

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>

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

[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,

When invoked this returns the following:

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:

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

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.

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

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:

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.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralHow to obfuscate a web service
SFWheeler
7:16 13 Mar '10  
Hi Chris,

Nice article! Can you provide any direction on obfuscation of the web service? I'd like to protect my business logic in the files I put on the server.

Thanks,
Scott
Generalhi maunder
abmv
9:53 19 Feb '10  
hi what brand of shades are those in your photo??? they look cool
Caveat Emptor.

"Progress doesn't come from early risers – progress is made by lazy men looking for easier ways to do things." Lazarus Long

GeneralRe: hi maunder
Chris Maunder
6:26 22 Feb '10  
Oakley bottlecap[^]

When one geek asks another geek for fashion advice you know something is very, very wrong. Wink
cheers,
Chris Maunder

The Code Project | Co-founder
Microsoft C++ MVP

GeneralHow to test the WebMethod by passing the parameter value in the URL
elizas
3:46 27 Jan '10  
To test a web method present inside a web service we need to call the web service through the browser and then invoke the web method. If the web method take some parameter then we have to provide it in the supplied text box
But with a little modification to the WebConfig file we can also pass the parameter in the url itself. The process is described as follow:

We have to add the following line of code inside the <system.web> tag of the WebConfig file.

<webServices>

<protocols>

<add name="HttpGet"/>

</protocols>

</webServices>

Then we can pass the parameter value by appending it to the url.

Ex: http://localhost:1115/v150/WebserviceTest.asmx/HelloUser?name=MFS

[Hope this will help you with your web method testing.]
thanks
Eliza
http://www.mindfiresolutions.com/how-to-test-the-webmethod-by-passing-the-parameter-value-in-the-url-787.php[^]

Cheers,
Eliza

GeneralError code snippet in your artical
LiShuangJiang
17:09 15 Oct '09  
Hello,

Thanks for your clearly introduction, but I find there is one code snippet in your demo need to be updated, please see my comments below

[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++)
{
//You forget to intialize each ClientData object.
//You should add : Clients[i]=new ClientData();
Clients[i].Name = "Client " + i.ToString();
Clients[i].ID = i;
}
}
return Clients;
}

Thanks,
Shuangjiang
GeneralRe: Error code snippet in your artical
Chris Maunder
17:20 15 Oct '09  
You may want to double check there. Remember ClientData is a struct, not a class.

cheers,
Chris Maunder

The Code Project Co-founder
Microsoft C++ MVP

GeneralRe: Error code snippet in your artical
LiShuangJiang
17:24 15 Oct '09  
:( Sorry for my careless mistake..
GeneralDiscovery files
vishwjeet
2:52 6 Aug '09  
Hi,
I have tried out searching everywhere but I am not able to get satisfactory articles on the discovery files(disco/vsdisco). Can you guide me to some good links, or if you have time can you throw some light on them.

Thanks
GeneralWell Done!
TW Burger
16:17 9 Jul '09  
Clear and thorough introduction to the concept of .NET Web services. Thanks.Thumbs Up

TW Burger

GeneralQuery regarding Service
pratap557
3:22 8 Jul '09  
Dear Mr. Chris,

I am going to develop a windows service, which will use web service for mailing, SMS. But I would like to develop the application in such a way that , if user puts web service detail in a config file where the windows service is installed , the windows service will automatically call the web service [i.e. dynamic changes at runtime].

I am using ASP.NET 2008

How can I proceed , Please suggest in this regard.

Pratap
QuestionError Occurs while running this application
Narendra Reddy Vajrala
5:40 12 Mar '09  
I successfully build this application but while running it is taking number but giving the fallowing Error

eption: Index was outside the bounds of the array.
at WebService1.Service1.GetEmployee(Int32 Num) in D:\naren\WEBSERVICES_EX\WebService1\WebService1\Service1.asmx.cs:line 41

What it means Please respond.
Confused
GeneralWebservice
praveen_varma
23:21 7 Jan '09  
Hi

I want to create a web application that has a button called Invoke

Now, if I click on this Invoke button, this should call the web service

can someone give me an example as a project in C# ?

Please help !!

Regards
Praveen
GeneralNot able to create Web Services, please help!
drshreya
12:59 17 Dec '08  
Thank you very much for the wonderful article. Since I am totally new to Web applications, I have a beginners question. I have VS 2008 and IIS installed in my system. I am not able to create web application by selecting the location as http. It lets me choose only local drive, please let me know what I am doing wrong.

Thanks,
Sreya
GeneralGood article
Donsw
10:47 15 Dec '08  
Good article, I had forgotten the cache timeout value. Smile
GeneralApplying Security on a C# webservice
Cpweart
1:02 24 Nov '08  
Hi,

I have created a webservice in C# 2.0 .net environment,
that accepts xml doc that has values to be saved in a sql db.
How do I go about enforcing Security on my web service.
NB: I am new on the .net environment. Big Grin
GeneralTest your web service
Member 1652487
0:05 17 Oct '08  
Develope and test web service is sometime difficult.
I use a tool named SOAPbox to test my web services and it is very helpful.
You can load your WSDL file and then execute some tests as if you were a customer of your service. This help me to correct, modify or improve my service before put it online.
You can also test the authentication of your service, inject malicious code and stress test your services.
This tool is provided by Vordel, an expert company in XML Gateway and web security.
You can try it here : http://www.vordel.com/products/soapbox/
GeneralRe: Test your web service
Troy Russell
9:07 24 May '09  
Hey,

   I was sittin' here & wondering if at :
http://www.vordel.com/products/soapbox/ is my confermations equil nouph or not.


                                    Troy
Questionchanging the web service
qin__23
6:24 1 Aug '08  
Hi,

If I add new methods to the web service, but some older clients will not be using them, do the old clients need to recompile?
Thanks.

qin__23
Generalhow to check web service connected successfully or not in c#
lucluv
22:28 1 Jul '08  
my application is connecting to a web service by creating webservice object and call the method.This application starts through sql job.But if web service method call fails the i want to re-connect with service againg (say 4 times).How can i check whether web service get connected successfully or not.

please respond
GeneralRe: how to check web service connected successfully or not in c#
John Simmons / outlaw programmer
5:48 27 Aug '08  
You could include a do-nothing method in your web service that you could call just to make sure it's connected correctly. On the other hand, you could surround the web service access code wit a try/catch bock and just handle th4e exception.

"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
-----
"...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

Generalweb service
anusatya
0:21 8 Mar '08  
i am designing an web application, i want the web service should call
the web form dynamically Smile
GeneralProblem with the classes HttpWebRequest and HttpWebResponse sous C#
zouzoulikou
5:39 14 Aug '07  
Hi !
I'm a newbie with webservices. I must read a string in a XML file, but I must log on a server.
And I don't want that the login window appears. Please help me. Here is my XML File :



0
IThdpC1uuYwkiKGeMiuFMSZ56qUvf8BXGt3Sej284iE8jxogh5lkWwauawWvT78-
200


To access to the resource, I must type this link in Internet Explorer :

http://mysociety.com/EmtGateway/SessionService.asmx/GetSID[^]


Here is the code I execute :

public bool ConnectServer(String sServer, String sConnexion, String sLogin, String sPwd)
{
m_bIsServerNG = false;
bool bSucceed = false;
DateTime dt1 = DateTime.Now;
try
{
m_sServer = sServer;

// Prepare session id provider URL
String sUrlSessionIdProvider = sConnexion;
String SUrlSuffix = String.Format("?username={0}&password={1}", sLogin, sPwd);
sUrlSessionIdProvider += SUrlSuffix;

// Build xml request to get session id
HttpWebRequest httpConnectionRequest = (HttpWebRequest)WebRequest.Create(sUrlSessionIdProvider);

NetworkCredential myCredential = new NetworkCredential(sLogin, sPwd);
CredentialCache credentialLog = new CredentialCache();
credentialLog.Add(new Uri(sUrlSessionIdProvider), "Basic", myCredential);
httpConnectionRequest.Credentials = credentialLog;

httpConnectionRequest.Method = "GET";
httpConnectionRequest.ContentType = "text/xml; charset=utf-8";
httpConnectionRequest.UserAgent = "MyAgentSingleSignOn";

// Get request response
HttpWebResponse httpConnectionResponse = (HttpWebResponse)httpConnectionRequest.GetResponse();
Stream streamResponse = httpConnectionResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);

// Load response in an XML Document
XmlDocument doc = new XmlDocument();
doc.LoadXml(streamReader.ReadToEnd());

// Select session id
XmlNode root = doc.DocumentElement;
XmlNode nodeSid;
nodeSid = root.SelectSingleNode("*[local-name()='sid']");

if (nodeSid != null)
{
m_sessionId = nodeSid.InnerText;
bSucceed = true;
}

streamResponse.Close();


}
catch (WebException e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
catch (System.Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}

TimeSpan ts = DateTime.Now - dt1;

m_errorHandler.setErrorLog("Connect to server", bSucceed ? "Succeeded" : "Failed", ts.Milliseconds.ToString());
return bSucceed;
}

this code launch an exception
("The remote server returned an error: (401) Unauthorized.")

And here is what I see in the description error :

Headers {XXX-Authenticate: CGIPassword
Connection: close
Content-Type: text/html; charset=ISO-8859-1
Date: Mon, 13 Aug 2007 17:14:34 GMT
Set-Cookie: Transact=H37862c891bbc17f4a1588c67319b0f50:session_id=a9f37dfc49c011dc890ab3bdee1a94e9&first_time=1&kid=310001.100014&ss=env; Path=/
Server: Netscape-Enterprise/3.6 SP3
WWW-Authenticate: Basic realm="MySociety Account Administration"

}

any Idea ?

Tell me what coding language you use, I'll tell you what coder you are
GeneralWant to use xml web service from another website database
Abhisriv
1:32 2 Aug '07  
Dear sir,
Actually, I am developing a website on which i need to use the database on another site which is currently running.
i.e, I need to use xml web services on my site.
So, kindly support me and give me an overview by which I can access the xml web service of another client.
Waiting for your response.
Its very urgent.
Thnks and regards
Bunty


Buntysriv
GeneralUse SOAP protocol to access Internet Database Server [modified]
nguyenthanhtungtinbk
13:13 6 Jul '07  
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
Generalhow to call this web service from C#
anhpqvn
23:49 7 Jun '07  
your webservice's method return an array.
So, could you please tell me how to call it and display results from an asp.net page.
thank you!


Last Updated 6 Jun 2002 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010