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:
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 stores 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 in 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 discus the procedure.
  • EnableSession property

This property allows enabling of the session in a 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:
  1. 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:
  1. [WebMethod (EnableSession=true)]  
  2.     public int GetAddition(int Number)   
  3.     {  
  4.   
  5.      //Session tasks  
  6.     } 
 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 need to inherit the Web Service class from 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#" - "ASP.NET Empty Web Application" (to avoid adding a master page).
  3. Provide the web site 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 discusing it in details.

Now after adding the web service template then the Solution Explorer will look such as follows.
 
 
Since 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:
  1. public class Customer : System.Web.Services.WebService  
  2. {  
  3.     //to Enable session it must to set EnableSession=true  
  4.     [WebMethod (EnableSession=true)]  
  5.     public int GetAddition(int Number)   
  6.     {  
  7.         //cekcing wheter the session is null  
  8.         if (Session["GetAddition"] == null)  
  9.         {  
  10.             //set session value to 0 if session is null  
  11.             Session["GetAddition"] = 0;  
  12.           
  13.         }  
  14.         else  
  15.         {  
  16.             //Add the user Input value into the existing session value  
  17.             Session["GetAddition"] = (int)Session["GetAddition"] + Number;  
  18.           
  19.           
  20.         }  
  21.         //returen the session value  
  22.         return (int)Session["GetAddition"];  
  23.     }  
  24.      
  25.       

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 am storing the user Input values into the session and assigning 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 such as follows:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  6.   
  7. [WebService(Namespace = "http://tempuri.org/")]  
  8. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  9.   
  10. //To support Session in Web service then session class must be inheited from   
  11. //System.Web.Services.WebService  
  12. public class Customer : System.Web.Services.WebService  
  13. {  
  14.     //to Enable session it must to set EnableSession=true  
  15.     [WebMethod (EnableSession=true)]  
  16.     public int GetAddition(int Number)   
  17.     {  
  18.         //cekcing wheter the session is null  
  19.         if (Session["GetAddition"] == null)  
  20.         {  
  21.             //set session value to 0 if session is null  
  22.             Session["GetAddition"] = 0;  
  23.           
  24.         }  
  25.         else  
  26.         {  
  27.             //Add the user Input value into the existing session value  
  28.             Session["GetAddition"] = (int)Session["GetAddition"] + Number;  
  29.           
  30.           
  31.         }  
  32.         //returen the session value  
  33.         return (int)Session["GetAddition"];  
  34.     }  
  35.      
  36.       

Now let us create the UI with the a 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 .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:

 
 
Now add a button and a TextBox to the Default.aspx page body section, then it will look as follows:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body style="background-color:Blue">  
  10. <h4 style="color:White">Article by Vithal Wadje</h4>  
  11.     <form id="form1" runat="server">  
  12.     <table style="margin-top:90px;color:White">  
  13.     <tr>  
  14.     <td>Enter Value</td>  
  15.     <td>   
  16.         <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>  
  17.     </tr>  
  18.     <tr>  
  19.     <td></td><td></td>  
  20.     </tr>  
  21.      <tr>  
  22.     <td></td><td>  
  23.         <asp:Button ID="btngetAddition" runat="server" Text="Get Addition"   
  24.              onclick="btngetAddition_Click" /> </td>  
  25.     </tr>  
  26.     <tr>  
  27.     <td>  
  28.       
  29.     </td>  
  30.     <td id="tdoutput" runat="server">  
  31.       
  32.     </td>  
  33.     </tr>  
  34.     </table>  
  35.     </form>  
  36. </body>  
  37. </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 about it again:
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:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. public partial class _Default : System.Web.UI.Page  
  9. {  
  10.     protected void Page_Load(object sender, EventArgs e)  
  11.     {  
  12.   
  13.     }  
  14.     protected void btngetAddition_Click(object sender, EventArgs e)  
  15.     {  
  16.         Customer obj = new Customer();  
  17.   
  18.         tdoutput.InnerText =Convert.ToString(obj.GetAddition(Convert.ToInt32(TextBox1.Text)));  
  19.     }  

Now run the application, the initial UI will look as follows:
 
 
 
Now enter a value into the preceding TextBox and click on the Get Addition button, for an examle I will enter 1 as in the following:
 
 
 
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:
 
 
 
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:
 
 
 
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. 

Up Next
    Ebook Download
    View all
    Learn
    View all