Sunday 12 January 2014

Create a asp.net webservice and invoke using client.

In this article we are going to see the how to create a web service and invoke a web service from the client.
Create a new project with web service as template. in these we are creating a two methods which will have to do the maths operation.

Web Service :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Runtime.Remoting.Messaging;
using System.Web.Services.Protocols;
using System.IO;
using System.Threading;

namespace MathService
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.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 MathService : System.Web.Services.WebService
    {

        [WebMethod]
        public int Add(params int[] values)
        {
            return values.Sum();
        }

        [WebMethod]
        public int Sub(int a,int b)
        {
            return a - b;
        }

    }
}



Host the application in the IIS and launch the in the web browser.



Client:
Create a new project with the console application.Add the web reference and name it as Maths.

namespace InvokeWebService
{
    class Program
    {
        static void Main(string[] args)
        {
            Maths.MathService websrv = new Maths.MathService();
            Console.WriteLine("Connecting service . . . ");           
            int addvalue = websrv.Add(new int[] { 3,2,6,7});
            Console.WriteLine(" Add Operation result : " + addvalue);

            int subvalue = websrv.Sub(4, 2);
            Console.WriteLine(" Sub Operation result :" + subvalue);

            Console.WriteLine("Done");
            Console.Read();

        }
    }
}


Output:
Connecting service . . .
 Add Operation result : 18
 Sub Operation result :2
Done


From this article you can learn how to create the service and invoke it from the client.

No comments:

Post a Comment