You are on page 1of 2

Here's an example of how to create and consume an ASP.

NET Web Service to perform


the addition of two numbers:

1. Open Visual Studio and create a new ASP.NET Web Service Application project.
2. In the Solution Explorer, right-click on the project and select "Add" -> "Web
Service". Name it as "AdditionService".
3. In the code-behind file for the Web Service (AdditionService.asmx.cs), add the
following code to define the addition method:

using System;
using System.Web.Services;

namespace AdditionService
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class AdditionService : System.Web.Services.WebService
{
[WebMethod]
public int Add(int a, int b)
{
return a + b;
}
}
}

4. Build the Web Service project.


5. To test the Web Service, run the project and navigate to the .asmx file in a web
browser. You should see the Web Service's default page, which lists all available
methods.
6. To consume the Web Service, create a new ASP.NET Web Application project.
7. In the Solution Explorer, right-click on the project and select "Add Service
Reference".
8. In the "Add Service Reference" dialog, enter the URL to the Web Service and click
"Go". The Web Service should be discovered and its methods listed. Give it a
namespace name and click "OK".
9. In the code-behind file for a Web Form in the ASP.NET Web Application project,
add the following code to consume the Web Service:
using System;
using System.Web.Services.Protocols;

namespace AdditionClient
{
public partial class AdditionForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

protected void Button1_Click(object sender, EventArgs e)


{
int a = Convert.ToInt32(TextBox1.Text);
int b = Convert.ToInt32(TextBox2.Text);

AdditionService.AdditionServiceClient client = new


AdditionService.AdditionServiceClient();
int result = client.Add(a, b);

Label1.Text = result.ToString();
}
}
}

10. Build and run the ASP.NET Web Application project. The result of the addition
should be displayed in a label on the Web Form.

You might also like