C#.NET: How to create ASP.NET web service


Hi Friends,
 Here i am writing a code for Web services means how to create and user a simple example of web services into your asp.net application using C#.
 
To create your first web service project, just follow these steps:
1. Open your Visual Studio .NET and click File > New Website. This will display the project templates. Choose ASP.NET Web Service from the installed templates as shown below.



2. Visual Studio .NET should generate your first Hello web service method. Lets add another web service method.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

namespace WebService1
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public int AddTwo(int n1,int n2)
        {
            return n1 + n2;
        }
    }
}

if you can notice the obvious difference of our web service method with an ordinary C#  method is this additional attribute before the function name:
[WebMethod] //this will indicate that this is a Web service method


It tells the framework that the following method is a web service.

3. To test the web service project, Click the Start Debugging Visual Studio will automatically open your default web browser and display all available web service method.








4. Now lets test one of the web service method. Click the Addthis method. You should be forwarded to the following page:




AddThis requires two parameters. Try to put numbers on each textbox then click Invoke. The web service method will return an XML result like the one below:



After Creating this web Services you can use this web services into your web application lets take an example for that , I have a button on the click event I simple user the Web services with Add Method ,

protected void Button1_Click(object sender, EventArgs e)
        {
            Service1 obj = new Service1();
            Label1.Text = obj.AddTwo(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text)).ToString(); ;

        }
Here Service1 is the Webservice file name 

Hope this code also Helps you

Regards,
Rajesh 

0 comments: