Click here to Skip to main content
15,860,943 members
Articles / Web Development / ASP.NET

Understanding the Basics of Web Service in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.83/5 (105 votes)
10 Jun 2012CPOL5 min read 580.9K   10.1K   143   70
Understanding the need for a web service, the benefits of having a web service and how we can create a basic web service and consume it.

Introduction

This article aims at understanding the need for a web service, the benefits of having a web service and how we can create a basic web service and consume it.

Background

Connectivity between applications is very important. Connectivity in any case is very important for that matter but it specially is very important between applications. Connecting web application used to be a big challenge before the advent of technologies like SOAP (Simple Object Access Protocol). The reason it was so difficult was, there were so many technologies people were working in. The applications were hosted on different types of servers, etc. But these things should not be a barrier to facilitate the communication between applications. The only requirement was to have some standards to follow and standard ways of doing things so that the applications become capable of communicating with other applications irrespective of the technologies used.

SOAP and Web Services

SOAP and XML created the solution for the problem that developers were facing before. SOAP is a standard XML based protocol that communicated over HTTP. We can think of SOAP as message format for sending messaged between applications using XML. It is independent of technology, platform and is extensible too.

We have SOAP and XML to give us connectivity between applications. Does it mean that I have to write XML and SOAP specific things myself to facilitate this communications? I could do that but that will be very time consuming and sometimes error prone too.

Where does Web Services come in picture? Well, Web services is the mechanism that ASP.NET framework provides to make it easy for us to write code to facilitate connectivity between applications. As ASP.NET developer, If I need an application that will be used by many other applications then I can simply decide to write a web service for it and ASP.NET framework will take care of doing the low level SOAP and XML work for us.

The other side of the coin is, if our ASP.NET application wants to use a web service, i.e., an application that is providing me SOAP based interface for communication. So what we are going to do now is write a small Web service to see how we can have our application communication-ready for other applications and secondly, we will try to consume a webservice to understand how we can use other applications from our application.

Web service article image

Creating a Web Service

Let us write a simple module that will provide basic arithmetic operations to other applications. The user of our application will have to provide us 2 numbers and we will perform the requested operation like Addition, Subtraction and Multiplication.

So, the first thing we need to do is to create our web service. We can do this by creating a website of type ASP.NET Web service. This will give us a skeleton to write our web service code in.

C#
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
}

The attribute WebService tells that this class contains the code for web service. The namespace is what is used to identify the web service. The WebMethod attribute specifies the methods which our web service is providing.

Let us now go ahead and write code to have our functions in this webservice.

C#
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service ()
    {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public int Add(int x, int y)
    {
        return x+y;
    }

    [WebMethod]
    public int Subtract(int x, int y)
    {
        return x - y;
    }

    [WebMethod]
    public int Multiply(int x, int y)
    {
        return x * y;
    }
}

We have a very basic web service implemented which can let the user have some basic arithmetic operations. Now to create the WebService binary, we will have to use the following command on Visual Studio Command Prompt.

>CSC /t:library /out:ArithmeticServiceImpl.dll App_code\Service.cs

This will create a DLL file for our web service. This DLL file can be used by any client by using the SOAP protocol. If we need to test our web service for how it works over the SOAP protocol, we can view the service.asmx file in the browser and see what functions our web service is exposing.

Web service article image

We can even test these methods here and see the XML file that contains the service description.

Consuming a WebService

There are three ways we can consume a WebService:

  1. Using HTTP-POST method.
  2. Using XMLHttp that will use SOAP to call our the service
  3. Using WSDL generated proxy class

The HTTP-Post method can be used by calling .asmx file directly from client. We can directly use the method name and the parameter names will be taken from our input fields on form.

HTML
<html>
    <body>
        <form action="http://localhost/.../Service.asmx/Multiply"  method="POST">
                <input name="x"></input>
                <input name="y"></input>

                <input type="submit" value="Enter"> </input>
        </form>
    </body>
</html>

When this form get submitted, the web service's method will be called. The second method where we can use the XMLHttp over SOAP to access the webservice is used when we want to use the web service using full capability of SOAP.

The third way of using the web service is by generating a Proxy class for the web service and then using that proxy class. This method is, to me, more type safe and less error prone as once we have the proxy class generated, it can take care of SOAP messages, serialization and ensure that all the problems can be handled at compile time instead of runtime.

To use this service, we need to do "Add Web reference" and add the webservice reference. Alternatively I can also use WSDL.exe, a command line tool, to generate the proxy classes and use them. "Add web Reference" is also using the same WSDL.exe to generate the proxy classes.

Web service article image

Now let us write some code to use the proxy class to perform the operations, the proxy class will then communicate to the web service using SOAP and get back the results to us.

C#
protected void Button1_Click(object sender, EventArgs e)
{
    if (txtX.Text != string.Empty
        && txtY.Text != string.Empty)
    {
        try
        {
            int x = Convert.ToInt32(txtX.Text);
            int y = Convert.ToInt32(txtY.Text);

            ArithmeticService.Service service = new ArithmeticService.Service();

            Label1.Text = "Sum: " + service.Add(x, y).ToString();
            Label2.Text = "Difference: " + service.Subtract(x, y).ToString();
            Label3.Text = "Multiplication: " + service.Multiply(x, y).ToString();
        }
        catch(Exception)
        {
            throw;
        }
    }
}

Let us run the website to see the results

Web service article image

Points of Interest

We saw how to create a web service in ASP.NET and how we can consume a web service in ASP.NET. One interesting area that we did not see here is how we can use web service from AJAX. ASP.NET also provides a mechanism using scriptManager that will generate the JavaScript proxy for a webservice and we can use it to call the webservice methods. Also, if we want to customize the security of our web service, we can do that too using custom SOAP headers.

History

  • 27 Feb 2012: Understanding the basics of Web Service in ASP.NET

License

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


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
Questionoccurred in App_Web_nsbige7m.dll but was not handled in user code. Please how to correct it Pin
Cihan Karim12-Mar-18 23:02
Cihan Karim12-Mar-18 23:02 
QuestionCan not run the code .. giving the following error Pin
Cihan Karim5-Mar-18 20:55
Cihan Karim5-Mar-18 20:55 
GeneralMy vote of 5 Pin
NF Khan6-Aug-16 20:32
NF Khan6-Aug-16 20:32 
Questionurl consume Pin
caradri15-Mar-16 3:39
caradri15-Mar-16 3:39 
AnswerRe: url consume Pin
caradri16-Mar-16 22:19
caradri16-Mar-16 22:19 
Questionhtm &sp Pin
ganeshmca8725-Jan-16 1:09
ganeshmca8725-Jan-16 1:09 
Questiongrid_crud_using_sp Pin
ganeshmca8725-Jan-16 1:06
ganeshmca8725-Jan-16 1:06 
QuestionA little guidance on [C# desktop application] web service to server script connection, please Pin
Kevin Barasa21-Oct-15 4:47
Kevin Barasa21-Oct-15 4:47 
GeneralMy vote of 4 Pin
gogonta1-Oct-15 5:06
gogonta1-Oct-15 5:06 
QuestionWeb Services Pin
lalit singh chauhan18-Aug-15 20:09
lalit singh chauhan18-Aug-15 20:09 
QuestionHow to use methods of my web site into webservice Pin
Member 116145311-Jun-15 0:37
Member 116145311-Jun-15 0:37 
i had my web site trackallresults.com and now i want to provide a webservice for that asp .net c# web site for android.
My Questions are
1. How to add a web service in my web site
2. How to use methods of my web site into web service

Please do help me!!!!!
AnswerRe: How to use methods of my web site into webservice Pin
Rahul Rajat Singh10-Jun-15 18:18
professionalRahul Rajat Singh10-Jun-15 18:18 
QuestionThanks Pin
Member 114573141-Apr-15 6:38
Member 114573141-Apr-15 6:38 
Questiongridview commendfield edit,delete,update Pin
mganesan198721-Dec-14 19:04
mganesan198721-Dec-14 19:04 
Questionlinks Pin
mganesan198728-Nov-14 0:26
mganesan198728-Nov-14 0:26 
Questioncomment Pin
shrikant mane22-Nov-14 21:25
shrikant mane22-Nov-14 21:25 
AnswerRe: comment Pin
Ramprit Sahani8-Apr-15 20:52
Ramprit Sahani8-Apr-15 20:52 
GeneralMy vote of 5 Pin
corvanica28-Oct-14 7:10
corvanica28-Oct-14 7:10 
Questionjquery validation Pin
mganesan19879-Oct-14 2:04
mganesan19879-Oct-14 2:04 
GeneralMy vote of 3 Pin
manish71022-Jul-14 19:07
manish71022-Jul-14 19:07 
GeneralMy vote of 1 Pin
Jignesh Khant6-May-14 1:22
Jignesh Khant6-May-14 1:22 
QuestionThanks for sharing nice article Pin
khaliqhamid2-May-14 19:00
khaliqhamid2-May-14 19:00 
Questionbasic grid edit delete update Pin
mganesan198724-Apr-14 18:01
mganesan198724-Apr-14 18:01 
QuestionMy vote of 5 Pin
GenadyT11-Apr-14 22:14
professionalGenadyT11-Apr-14 22:14 
Questionأحسنت Pin
Ayham Ȝllan10-Mar-14 22:44
Ayham Ȝllan10-Mar-14 22:44 

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.