Building Simple Web Services
At this point, I will show you, how to create a simple web service executed under .NET. In this example we define some methods in the UtilityWebService class. They are responsible for adding two integer values and displaying a "hello world" text as in the following:
1. Open
a Visual C# .Net website in the Visual Studio 2010 IDE.
2. Right-click
on the project name from the Solution Explorer and click add new item.
3. Choose
web service from the template and name it UtilityWebService.cs.
4. Thereafter,
implement additional method functionality in the class
"UtilityWebService.cs" as shown below:
C# web service code
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
C# web service code
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
///<summary>
/// Summary description for UtilityWebService
///</summary>
[WebService(Namespace ="http://tempuri.org/")]
[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
publicclass UtilityWebService : System.Web.Services.WebService {
/// Summary description for UtilityWebService
///</summary>
[WebService(Namespace ="http://tempuri.org/")]
[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
publicclass UtilityWebService : System.Web.Services.WebService {
public UtilityWebService () {
//Uncomment the following line
if using designed components
//InitializeComponent();
}
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public int addition(int a,int b)
{
return a+b;
}
}
public int addition(int a,int b)
{
return a+b;
}
}
5. It
is essential to add the [WebMethod] attribute before any new method definition.
6. Finally
build the project and see the output in the browser as in the following. You
will notice the methods here defined in the web service class.
7. Now
click over the addition method, enter some integer values in the text box for
adding them and invoke the web service class method as in the following:
8. Finally
see the addition result in the form of a XML file that is passed over the wire
through HTTP and compatible with almost every platform:
.NET Interview Questions
.NET Interview Questions