Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read session values using jQuery

I am using c# and jQuery.

I have below code where I am setting the Session Variable using C# code.

if (!string.IsNullOrEmpty(results))
{
    string[] array = results.Split(',');
    string firstName = array[0];
    string lastName = array[1];
    string activeCardNo = array[2];
    string memberShipTier = array[3];
    string accessToken = array[4];

    Session["skyFirstName"] = firstName.ToString();
    Session["skyLastName"] = lastName.ToString();
    Session["skyActiveCardNo"] = activeCardNo.ToString();
    Session["skyMemberShipTier"] = memberShipTier.ToString();
    Session["boolSignOn"] = "true";
    Response.Redirect(fromPage);
    Response.End();
}

Now I want to read these values (Session["skyFirstName"]) using jQuery so that I can set in my elements. Please suggest.

like image 743
Manoj Singh Avatar asked Aug 28 '26 18:08

Manoj Singh


1 Answers

Session values are stored on the server and it is impossible to read them with client side javascript. One way to achieve this would be to expose some server side script or generic handler which would return the corresponding session value given a key and then use jQuery to send an AJAX request to this handler and read the value. You should be aware that by doing this the user can read all his session values. Be warned that exposing the same script for writing session values could be catastrophic from security standpoint.

Here's an example:

public class ReadSession : IHttpHandler, IReadOnlySessionState
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        context.Response.Write(new JavaScriptSerializer().Serialize(new
        {
            Key = context.Request["key"],
            Value = context.Session[context.Request["key"]]
        }));
    }

    public bool IsReusable 
    { 
        get { return true; } 
    }
}

and then query it:

$.getJSON('/ReadSession.ashx', { key: 'skyFirstName' }, function(result) {
    alert(result.Value);
});
like image 184
Darin Dimitrov Avatar answered Aug 31 '26 06:08

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!