.NET Web Services Tutorial

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

Environment: .NET 1.0.3705, IIS 5.0

Introduction

Visual Studio .NET makes .NET programming simple and accelerates the development process. It hides a lot of repetitive and configuration details from the user and improves productivity. However, sometimes you would like to program for .NET without using VS .NET; for example, you want to learn .NET framework programming and do not have access to VS .NET or you want to know what is actually going on under the hood.

Writing a Web Service in .NET using VS .NET very is easy. However, it is possible to write Web Services using the plain .NET SDK. I struggled a lot to write Web Services without VS .NET and tried to find help on the Net. There are a lot of examples available for writing Web Services using VS.NET, but you will rarely find any examples of writing Web Services using only the .NET SDK. This article is exactly for this purpose. It looks at Web Services development using the .NET SDK alone.

We will write and publish a simple web Service. We will also write two Web Service consumers: one Web-based consumer (ASP.NET application) and another Windows application-based consumer. Let's start writing our first Web Service.

Writing a Web Service

Following is our first Web Service; it exposes two methods (Add and SayHello) as Web Services to be used by applications. This is a standard template for a Web Service. .NET Web Services use the .asmx extension. Note that a method exposed as a Web Service has the WebMethod attribute. Save this file as FirstService.asmx in the IIS virtual directory (as explained in configuring IIS; for example, c:\MyWebSerces).

FirstService.asmx
  <%@ WebService language="C" class="FirstService" %>

  using System;
  using System.Web.Services;
  using System.Xml.Serialization;

  [WebService(Namespace="http://localhost/MyWebServices/")]
  public class FirstService : WebService
  {
      [WebMethod]
      public int Add(int a, int b)
      {
          return a + b;
      }

      [WebMethod]
      public String SayHello()
      {
          return "Hello World";
      }
  }

To test a Web Service, it must be published. A Web Service can be published either on an intranet or the Internet. We will publish this Web Service on IIS running on a local machine. Let's start with configuring the IIS.

  • Open Start->Settings->Control Panel->Administrative tools->Internet Services Manager.
  • Expand and right-click on [Default Web Site]; select New ->Virtual Directory.
  • The Virtual Directory Creation Wizard opens. Click Next.
  • The "Virtual Directory Alias" screen opens. Type the virtual directory name—for example, MyWebServices—and click Next.
  • The "Web Site Content Directory" screen opens. Here, enter the directory path name for the virtual directory—for example, c:\MyWebServices—and click Next.
  • The "Access Permission" screen opens. Change the settings as per your requirements. Let's keep the default settings for this exercise. Click the Next button. It completes the IIS configuration. Click Finish to complete the configuration.

To test that IIS has been configured properly, copy an HTML file (for example, x.html) in the virtual directory (C:\MyWebServices) created above. Now, open Internet Explorer and type http://localhost/MyWebServices/x.html. It should open the x.html file. If it does not work, try replacing localhost with the IP address of your machine. If it still does not work, check whether IIS is running; you may need to reconfigure IIS and Virtual Directory.

To test our Web Service, copy FirstService.asmx in the IIS virtual directory created above (C:\MyWebServices). Open the Web Service in Internet Explorer (http://localhost/MyWebServices/FirstService.asmx). It should open your Web Service page. The page should have links to two methods exposed as Web Services by our application. Congratulations; you have written your first Web Service!!!

Testing the Web Service

As we have just seen, writing Web Services is easy in the .NET Framework. Writing Web Service consumers is also easy in the .NET framework; however, it is a bit more involved. As said earlier, we will write two types of service consumers, one Web- and another Windows application-based consumer. Let's write our first Web Service consumer.

Web-Based Service Consumer

Write a Web-based consumer as given below. Call it WebApp.aspx. Note that it is an ASP.NET application. Save this in the virtual directory of the Web Service (c:\MyWebServices\WebApp.axpx).

This application has two text fields that are used to get numbers from the user to be added. It has one button, Execute, that, when clicked, gets the Add and SayHello Web Services.

WebApp.axpx
  <%@ Page Language="C#" %>
  <script runat="server">
  void runSrvice_Click(Object sender, EventArgs e)
  {
      FirstService mySvc = new FirstService();
      Label1.Text = mySvc.SayHello();
      Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text),
                    Int32.Parse(txtNum2.Text)).ToString();
  }
  </script>
  <html>
  <head>
  </head>
  <body>
  <form runat="server">
    <p>
        <em>First Number to Add </em>:
        <asp:TextBox id="txtNum1" runat="server"
             Width="43px">4</asp:TextBox>
    </p>
    <p>
        <em>Second Number To Add </em>:
        <asp:TextBox id="txtNum2" runat="server"
             Width="44px">5</asp:TextBox>
    </p>
    <p>
        <strong><u>Web Service Result -</u></strong>
    </p>
    <p>
        <em>Hello world Service</em> :
        <asp:Label id="Label1" runat="server"
             Font-Underline="True">Label</asp:Label>
    </p>
    <p>
        <em>Add Service</em> :
        & <asp:Label id="Label2" runat="server"
               Font-Underline="True">Label</asp:Label>
    </p>
    <p align="left">
        <asp:Button id="runSrvice" onclick="runSrvice_Click"
             runat="server" Text="Execute"></asp:Button>
    </p>
  </form>
  </body>
  </html>

After the consumer is created, we need to create a proxy for the Web Service to be consumed. This work is done automatically by Visual Studio .NET for us when referencing a Web Service that has been added. Here are the steps to be followed:

  • Create a proxy for the Web Service to be consumed. The proxy is created using the wsdl utility supplied with the .NET SDK. This utility extracts information from the Web Service and creates a proxy. Thus, the proxy created is valid only for a particular Web Service. If you need to consume other Web Services, you need to create a proxy for this service as well. VS .NET creates a proxy automatically for you when the reference for the Web Service is added. Create a proxy for the Web Service using the wsdl utility supplied with the .NET SDK. It will create FirstSevice.cs in the current directory. We need to compile it to create FirstService.dll (proxy) for the Web Service.
    c:> WSDL http://localhost/MyWebServices/
                    FirstService.asmx?WSDL
    c:> csc /t:library FirstService.cs
    
  • Put the compiled proxy in the bin directory of the virtual directory of the Web Service (c:\MyWebServices\bin). IIS looks for the proxy in this directory.
  • Create the service consumer, which we have already done. Note that I have instantiated an object of the Web Service proxy in the consumer. This proxy takes care of interacting with the service.
  • Type the URL of the consumer in IE to test it (for example, http://localhost/MyWebServices/WebApp.aspx).

Windows Application-Based Web Service Consumer

Writing a Windows application-based Web Service consumer is the same as writing any other Windows application. The only work to be done is to create the proxy (which we have already done) and reference this proxy when compiling the application. Following is our Windows application that uses the Web Service. This application creates a Web Service object (of course, proxy) and calls the SayHello and Add methods on it.

WinApp.cs
  using System;
  using System.IO;

  namespace SvcConsumer{
  class SvcEater
  {
      public static void Main(String[] args)
      {
          FirstService mySvc = new FirstService();

          Console.WriteLine("Calling Hello World Service: " +
                             mySvc.SayHello());
          Console.WriteLine("Calling Add(2, 3) Service: " +
                             mySvc.Add(2, 3).ToString());
      }
  }
  }

Compile it using c:>csc /r:FirstService.dll WinApp.cs. It will create WinApp.exe. Run it to test the application and the Web Service.

Now, the question arises: How can I be sure that my application is actually calling the Web Service? It is simple to test. Stop your Web server so that the Web Service cannot be contacted. Now, run the WinApp application. It will fire a run-time exception. Now, start the Web server again. It should work. Great, isn't it?

Downloads

Download tutorial source code - 2 Kb


Comments

  • Change code to C#

    Posted by Rodrigo Muniz on 10/04/2012 06:44am

    If you change in first line "C" to "C#" it will work well.

    Reply
  • industrial training indore

    Posted by industrial training indore on 08/31/2012 05:38am

    It is really a nice and helpful piece of info. I’m glad that you simply shared this helpful info with us. Please keep us informed like this. Thank you for sharing. industrial training indore

    Reply
  • what is wrong

    Posted by emanuel on 05/22/2012 09:57am

    after reading the comments it looks like i am the only one that has an error, i am usisn IIS 6.1, windows 7, did the configuration but have an error where it says "'C' is not a supported language." Source File: /MyWebServices/FirstService.asmx Line: 1 what is wrong then?

    • Software Developer

      Posted by Andy Beckham on 10/08/2012 12:47pm

      I had to change the "C" to "C#" for it to work.

      Reply
    Reply
  • Windows live web service, developers survey

    Posted by Epler on 03/01/2012 10:20am

    I would like to have a small survey under the Windows live developers. The test is for a thesis where I study how a web service can be more accessible for developers. Give me 4 minutes of your precious time and join the survey here: https://docs.google.com/a/sense-os.nl/spreadsheet/viewform?formkey=dHZIOFhybURrMExMb3B1MjFzWXFVU1E6MQ#gid=0

    Reply
  • NET

    Posted by blueskysinger on 02/23/2012 01:31am

    Tank you for sharing. I'm all for your idea, with the programing of net can be better, it's easier for us to prgraming any thing! I currently managing to finish my programming to make a barcode generator by myself. That is a nice experience ,you may hava a try ,too.http://www.keepautomation.com/products/net_barcode/barcodes/qrcode.html

    Reply
  • Kind of the same problem with the EXE

    Posted by mike.anfinson@yahoo.com on 05/29/2010 04:35am

    Was wondering, although not much activity at this blog, so not really going to wait but just in case, anybody know how I'd splice a user id and password into the code or if that's how you do it, or how do you identify yourself to the service? using System; using System.IO; namespace SvcConsumer{ class SvcEater { public static void Main(String[] args) { FirstService mySvc = new FirstService(); Console.WriteLine("Calling Hello World Service: " + mySvc.SayHello()); Console.WriteLine("Calling Add(2, 3) Service: " + mySvc.Add(2, 3).ToString()); } } }

    Reply
  • WSDL username password parameters. Cease. Figured it out

    Posted by mike.anfinson@yahoo.com on 05/28/2010 03:24pm

    I'm sure I'm the sole ignoramus, but just in case, you may need to supply passwords if you set things up that way, again, I set up security, but sometimes I wonder for whom, what? Anyway yeah. So if you get the 401 error, could try this. Just replace username: and password: with valid credentials. I used the admin because, got stuck on something else unrelated to 401, so my overkill melt down procedures were in effect. Probably wouldn't need that much authority. C:\>wsdl /username:Administrator /password:abcdefg http://localhost/MyWebServ ices/FirstService.asmx?WSDL Microsoft (R) Web Services Description Language Utility [Microsoft (R) .NET Framework, Version 2.0.50727.3038] Copyright (C) Microsoft Corporation. All rights reserved. Writing file 'C:\FirstService.cs'.

    Reply
  • Trouble creating proxy?

    Posted by mike.anfinson@yahoo.com on 05/27/2010 01:39pm

    got this far, then when I got too the WSDL cmd, see below Is there a C# .net programmer in the house who could possibly give some advice? I kind of tried to give it credentials, thinking that may be something to it, but not providing them correctly with the WSDL, plus not totally sure that's what's up, or what I'm really doing. Copyright (C) Microsoft Corporation. All rights reserved. Error: There was an error processing 'http://localhost/MyWebServices/FirstServic e.asmx?WSDL'. - There was an error downloading 'http://localhost/MyWebServices/FirstService. asmx?WSDL'. - The request failed with HTTP status 401: Access Denied. If you would like more help, please type "wsdl /?".

    Reply
  • Web Service inquiry for Medicines

    Posted by tjdarth on 04/27/2010 05:37pm

    Thanks for the good article. I've been looking for just such information to use as a refresher course to help me in my personal web service develoment effort. I would like to see if anyone on this thread might know where I could fine a medical medicen web service provider just like Xignite finanical services environment? Thanks again for this artial.

    Reply
  • This is great start point for webservice development

    Posted by Ranjan.net on 10/03/2008 12:28am

    This article has all what one will get through a classroom. It is self describing, simple and easy to follow solution. It is very rare to find such good articles. Thank you a lot.....

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date