Thursday, October 13, 2016

How to use session in a web service?

Add Customer.cs file...

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)]

//To support Session in Web service then session class must be inheited from
//System.Web.Services.WebService
public class Customer : System.Web.Services.WebService
{
    //to Enable session it must to set EnableSession=true
    [WebMethod (EnableSession=true)]
    public int GetAddition(int Number)
    {
        //cekcing wheter 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;             
        }
        //returen the session value
        return (int)Session["GetAddition"];
    }    
}
Customer.asmx
<%@ WebService Language="C#" CodeBehind="~/App_Code/Customer.cs" Class="Customer" %>
Default.aspx design
<%@ 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:60px;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>
  Addition
    </td>
    <td id="tdoutput" runat="server">
   
    </td>
    </tr>
    </table>
    </form>
</body>
</html>
Default.cs
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)));
    }
}
Web.config file
<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
</configuration>