In this article I will explain with an example, how to use Session inside WebMethod in ASP.Net using C# and VB.Net.
 
 
HTML Markup
The HTML Markup consists of:
TextBox – For capturing username.
Button – For setting TextBox value in Session.
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnSet" type="button" value="Set Session" />
 
 
Sending the value of variable to WebMethod using jQuery AJAX
The Set Button has been assigned a jQuery Click event handler.
Inside the Click event handler, an AJAX call is made to the SetSession WebMethod using jQuery AJAX and the value of the UserName TextBox is sent to the WebMethod.
Finally, the WebMethod returns a string which is displayed using JavaScript Alert Message Box.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btnSet").click(function () {
            $.ajax({
                type: "POST",
                url: "Default.aspx/SetSession",
                data: '{name: "' + $("[id*=txtUserName]").val() + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(response.d);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    });
</script>
 
 
Server Side Web Method
Inside the SetSession WebMethod, the value sent from the Client Side is received as parameter and is set into the Session variable.
Finally, the value is read back from the Session variable and sent back to the Client along with Current Server’s Date and Time in string format.
Note: The method is declared as static (C#) and Shared (VB.Net) and also it is declared as WebMethod unless you do this you won’t be able to call the methods.
 
C#
[System.Web.Services.WebMethod]
public static string SetSession(string name)
{
    HttpContext.Current.Session["Name"] = name;
    return "Hello " + HttpContext.Current.Session["Name"] + Environment.NewLine + "The Current Time is: " + DateTime.Now.ToString();
}
 
VB.Net
<System.Web.Services.WebMethod>
Public Shared Function SetSession(ByVal name As String) As String
    HttpContext.Current.Session("Name") = name
    Return "Hello " & HttpContext.Current.Session("Name") & Environment.NewLine & "The Current Time is: " & DateTime.Now.ToString()
End Function
 
 
Screenshot
Using Session inside Web Method in ASP.Net
 
 
Browser Compatibility

The above code has been tested in the following browsers.
Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads