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

 
AnswerRe: mabahong indiano Pin
Rahul Rajat Singh5-Dec-13 20:13
professionalRahul Rajat Singh5-Dec-13 20:13 
QuestionDanish Habib Pin
Malikdanish23-Aug-13 2:26
professionalMalikdanish23-Aug-13 2:26 
GeneralMy vote of 5 Pin
ketan italiya13-Aug-13 20:23
ketan italiya13-Aug-13 20:23 
GeneralMy vote of 5 Pin
prema_r28-Jul-13 0:38
prema_r28-Jul-13 0:38 
QuestionThanks Rahul Pin
Member 994161423-Jul-13 11:13
Member 994161423-Jul-13 11:13 
GeneralMy vote of 5 Pin
Qadri Jillani3-Jul-13 19:16
Qadri Jillani3-Jul-13 19:16 
Questionweb services Pin
Qadri Jillani3-Jul-13 19:14
Qadri Jillani3-Jul-13 19:14 
GeneralMy vote of 3 Pin
GreatOak27-Jun-13 2:01
professionalGreatOak27-Jun-13 2:01 
Wasn't really all the informative. Rahul usually is more detailed.
Generalvery good and understanding article Pin
AmrutaKanvinde20-Jun-13 14:41
AmrutaKanvinde20-Jun-13 14:41 
GeneralVery Nice Article Pin
Lalit PB31-May-13 0:42
Lalit PB31-May-13 0:42 
GeneralVery nice article Pin
Rasul Gani11-Apr-13 21:29
Rasul Gani11-Apr-13 21:29 
GeneralRe: Very nice article Pin
vijaykaliyaperumal23-May-13 3:46
vijaykaliyaperumal23-May-13 3:46 
GeneralMy vote of 5 Pin
ajis23262-Apr-13 23:36
ajis23262-Apr-13 23:36 
GeneralMy vote of 5 Pin
sagmali25-Mar-13 4:25
sagmali25-Mar-13 4:25 
GeneralMy vote of 5 Pin
Kr.Prakash19-Mar-13 23:43
Kr.Prakash19-Mar-13 23:43 
GeneralMy vote of 5 Pin
Nikhil_S10-Mar-13 19:52
professionalNikhil_S10-Mar-13 19:52 
Questionvoted 5 Pin
Anurag Sinha V6-Jan-13 22:41
Anurag Sinha V6-Jan-13 22:41 
AnswerArticle of the Day on Microsoft's site Pin
Rahul Rajat Singh3-Jan-13 18:53
professionalRahul Rajat Singh3-Jan-13 18:53 
GeneralMy vote of 3 Pin
Jasmin akther Suma28-Dec-12 7:47
Jasmin akther Suma28-Dec-12 7:47 
GeneralMy vote of 4 Pin
Karteek Murthy29-Nov-12 19:21
Karteek Murthy29-Nov-12 19:21 
GeneralVery Nice Article Pin
Vijay Raghava Reddy29-Nov-12 1:23
Vijay Raghava Reddy29-Nov-12 1:23 
QuestionWhere do you place Button1_Click Pin
jarr0d12-Nov-12 10:27
jarr0d12-Nov-12 10:27 
AnswerRe: Where do you place Button1_Click Pin
jarr0d12-Nov-12 10:34
jarr0d12-Nov-12 10:34 
QuestionNice straight forward easy to understand article Pin
Eddy Jawed23-Sep-12 10:00
Eddy Jawed23-Sep-12 10:00 
General000 Pin
vasanthamateti27-Aug-12 21:21
vasanthamateti27-Aug-12 21:21 

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.