Session Management In Web Service

Background

Managing the state of a request in a web application is very important because, as we know, most of the web applications that use the HTTP protocol (which is a stateless protocol, meaning that a previous request is not remembered automatically) need to be maintained manually using various state management techniques. Right now in this article, we will learn how to maintain the state in a web service. So let us learn step-by-step so beginners can also understand.

If you are new to Web Services then please refer to my following articles.

  1. Introduction to Web Service with Example in ASP.Net
  2. Web Service Method Attribute Properties
  3. Consuming Web Service in Web Application

I hope you have read those articles. Now let us start from a definition.

Sessions

A Session is one of the server-side state management techniques that store the user-specific data across the user request.

Key points Web Service Session

  1. By default a session is not enabled in a web service; we need to enable it using the following procedure.
  2. The default time out of the session is 20, the same as any web application.
  3. A Session is defined on the Web. config file, similar to any web application.
  4. The default session mode is Inproc in which session data is saved to the IIS worker process.

Enabling Session in Web Service

Since I have already said that by default a session is not enabled in a web service, we need to enable it with the following procedure. So let us discuss the procedure.

EnableSession property

This property allows enabling of the session in an XML web service and only those web service methods support a session derived from the class System.Web.Services.

Suppose the class name in a web service is Customer then after deriving from System.Web.Services the class will look such as follows.

public class Customer : System.Web.Services.WebService

The Enable session attribute is a boolean property having the values true or false, by default it is false. The following are the session modes supported by the web service method.

  1. InProc
  2. OutProc
  3. Custom
  4. Off.

The following example shows the syntax and example of the Enable Session property.

[WebMethod(EnableSession = true)]
public int GetAddition(int Number)
{
    // Session tasks
}

Notes

  1. To enable the session in a web service it must use the EnableSession Property of the WebMethod attribute.
  2. It must set EnableSession to true as shown in the preceding example.
  3. Without setting the EnableSession property to true, the session will not work otherwise the unhandled exception occurs.
  4. It must be needed to inherit the Web Service class from the system.Web.Services class as shown in the preceding class to support the session, otherwise it will not support the session.

Let us demonstrate the preceding points with an example by creating a web service as in the following.

  1. "Start","All Programs" "Microsoft Visual Studio 2010".
  2. "File", "New Project" "C#", and "ASP.NET Empty Web Application" (to avoid adding a master page).
  3. Provide the website a name such as "SessionInWebService" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer,  "Add New Item" then you will see the web service templates.

To learn in-depth about the web service please refer to my article Introduction to Web Service with Examples because in this article I am not discussing it in details.

Now after adding the web service template then the Solution Explorer will look such as follows.

Template

As we have seen in the preceding Solution Explorer, there is the Customer web service class with the Customer.asmx file. Now create the function that will enable the session and store the session value of the user request as in the following.

public class Customer : System.Web.Services.WebService
{
    //to Enable session it must to set EnableSession=true
    [WebMethod(EnableSession=true)]
    public int GetAddition(int Number)
    {
        //checking whether the session is null
        if (Session["GetAddition"] == null)
        {
            //set session value to 0 if session is null
            Session["GetAddition"] = 0;
        }
        else
        {
            //Add the user Input value into the existing session value
            Session["GetAddition"] = (int)Session["GetAddition"] + Number;
        }
        //return the session value
        return (int)Session["GetAddition"];
    }
}

Code Explanation

In the code above I have inherited the Customer web service class from the System.Web.Services.WebService class to support the session in the web service. Then to enable the session in the web service I have set the EnableSession property of the web service WebMthod Attribute to true. Then in the next line I created a function named GetAddition that takes the one integer input parameter.

In this function, I store the user Input values into the session and assigned again to the existing session value to check whether the session preserved the state during the user request and finally the addition of an existing session value and a new user input value is added and the results are returned to the user.

Now the entire code of the web service class will look as follows.

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

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Customer : System.Web.Services.WebService
{
    [WebMethod(EnableSession = true)]
    public int GetAddition(int Number)
    {
        if (Session["GetAddition"] == null)
        {
            Session["GetAddition"] = 0;
        }
        else
        {
            Session["GetAddition"] = (int)Session["GetAddition"] + Number;
        }
        return (int)Session["GetAddition"];
    }
}

Now let us create the UI with the simple web application so we can understand how the session is maintaining the state of the user request as in the following.

  1. Right-click on the existing Solution Explorer.
  2. Then choose Add New Item.
  3. Select the .aspx Page from the template list, define the name, and click on OK.

After adding the Default.aspx page into the existing web service Solution Explorer then it will look as follows.

Web service

Now add a button and a TextBox to the Default.aspx page body section, then it will look as follows.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title></title>  
</head>  
<body style="background-color: Blue">  
    <h4 style="color: White">Article by Vithal Wadje</h4>  
    <form id="form1" runat="server">  
        <table style="margin-top: 90px; color: White">  
            <tr>  
                <td>Enter Value</td>  
                <td>   
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>  
            </tr>  
            <tr>  
                <td></td><td></td>  
            </tr>  
            <tr>  
                <td></td><td>  
                    <asp:Button ID="btngetAddition" runat="server" Text="Get Addition"    
                               onclick="btngetAddition_Click" /></td>  
            </tr>  
            <tr>  
                <td>  
                      
                </td>  
                <td id="tdoutput" runat="server">  
                      
                </td>  
            </tr>  
        </table>  
    </form>  
</body>  
</html>

Now to learn how to consume the web service in a web application, please refer to the following article of mine because in this article I am not going to explain it again.

Consuming Web Service in Web Application.

Now, I hope you have read that article. Let us create the object of the web service class Customer in the Default.aspx page to access the method that is defined in the web service. After creating the object the default.aspx class file code will look as follows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }
    protected void btngetAddition_Click(object sender, EventArgs e)
    {
        Customer obj = new Customer();

        tdoutput.InnerText = Convert.ToString(obj.GetAddition(Convert.ToInt32(TextBox1.Text)));
    }
}

Now run the application, the initial UI will look as follows.

 Initial UI

Now enter a value into the preceding TextBox and click on the Get Addition button, for an example I will enter 1 as in the following.

 TextBox

The output of the preceding input value is 0 because we have set the condition in our web service class such that if the session is null then set the session value to zero. So in our first request to the web service, the session value is null.

Now enter 97 and click on the Get Addition button and the output will be as follows.

 Addition button

The output of the preceding input value is 97 because the previous value in the session was 0. Now enter 103 and the output will be as follows.

Output

The output of the preceding 103 input value is 200 because the previous value of Session was 97 and this input value is 103 and the addition of these two is 200. Now from all the preceding examples, it's clear that the session is preserving the values of the user request in the session, hence it proves that we can also maintain the session in a Web Service.

Notes. Download the Zip file from the attachment for the full source code of the application.

Summary

I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.


Similar Articles