Friday, January 17, 2014

Session in WebService

Usually, when you think of a Web Service, you think …make the call, get the response, and get on with the task at hand. These "one shot" calls are the norm in Web Services but there may be times when you need a little more. You may need the Web Service to remember states between calls.

Example :

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;

namespace DemoWebService
{
    [WebService(Namespace = "http://AcmeWidgets.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    public class MyDemo : System.Web.Services.WebService
    {
        [WebMethod (EnableSession = true)]
        public string HelloWorld()
        {
            // get the Count out of Session State
            int? Count = (int?)Session["Count"];

            if (Count == null)
                Count = 0;

            // increment and store the count
            Count++;
            Session["Count"] = Count;

            return "Hello World - Call Number: " + Count.ToString();
        }
    }
}

We need EnableSession = true attribute to use Session in Web Service.







How To Call it From Client :

protected void Button1_Click(object sender, EventArgs e)
{
    localhost.MyDemo MyService;

    // try to get the proxy from Session state
    MyService = Session["MyService"] as localhost.MyDemo;

    if (MyService == null)
    {
        // create the proxy
        MyService = new localhost.MyDemo();

        // create a container for the SessionID cookie
        MyService.CookieContainer = new CookieContainer();

        // store it in Session for next usage
        Session["MyService"] = MyService;
    }

    // call the Web Service function
    Label1.Text += MyService.HelloWorld() + "
";
}

Output :
Hello World - Call Number: 1
Hello World - Call Number: 2
Hello World - Call Number: 3

Need to store the Service Object in Session Otherwise it will create a new object for each click. And output will be like this.

Hello World - Call Number: 1
Hello World - Call Number: 1
Hello World - Call Number: 1

Because session id will be different each time. You also need to create Container for SessionID.

In a Windows Forms application this is easy. Make the proxy global or static…just don't put it on the stack. For a Web Application it's a bit trickier, we put the proxy into the Session collection.

No comments:

Followers

Link