Creating and Using Web Service in Visual Studio 2010 using C#

This blog explains basic knowledge abut how to create and use web services.

Create WebService

  1. Open Visual Studio 2010
  2. Click on New project Link on start page
  3. New Project Window Will Open
  4. Select Web Application in the template window
  5. Enter the name of project
  6. Click on ok button
  7. Open Solution Explorer of your project
  8. Right click on project, the pop window will open
  9. Drag cursor on to add menu, the submenu of add menu will open, click on NewItem or Go to Add->NewItem.
  10. The AddNew Item Window will open, Select WebService and Rename WebService1.asmx to MyWebService.asmx, then click on ok button.
  11. The MyWebService.asmx file will appear in the solution explorer, open MyWebService.asmx file
  12. Declare your own method in this file bellow the HellowWorld function. You can remove the HellowWorld function from the WebService.

    For Example : the bellow function generate a random number and returns to it.

    [WebMethod(Description = "Get Random Number")]//Description about web method

    public string GetNumber() // Declaration of Method


        Random RM=new Random();

        return RM.Next(1,100).ToString();


    [WebMethod(Description = "Adds Two Number And return result")]

    public string Add(int firstno, int secondno)


        double result = firstno + secondno;

        return result.ToString();

    This is the all about create web service in your project, and then we will discuss about how to use or consume web service in your application.

Consume Web Service

  1. Right click on your WebService i.e MyService.asmx and click on Browse With. The Browser with window will open, select your installed explorer, for example select Internet Explorer.
  2. Copy the URL adder from the URL of browser.
  3. Right click on your project, click AddServiceReference , the Service Reference Window will open.
  4. Past the copied URL address in the address textbox of service reference window. click to 'Go' button
  5. Rename the Namespace as required and then Press ok.
  6. The reference of the Webservice will be appear in the Service Reference folder in solution explorer.
  7. Go to the default page of your project, take one label, set the text to 'Random Number'.
  8. Take another label control set this text as '0' and id as 'lblRandom'.
  9. Take a button set the text to 'Get ' and write the following code in the click event of the Button.

    MyWebService.MyService MS = new MyService();
    Label1.Text= MS.GetNumber();