How can I access session in a webmethod?

C#Session

C# Problem Overview


Can i use session values inside a WebMethod?

I've tried using System.Web.Services.WebMethod(EnableSession = true) but i can't access Session parameter like in this example:

    [System.Web.Services.WebMethod(EnableSession = true)]
    [System.Web.Script.Services.ScriptMethod()]
    public static String checaItem(String id)
    { 
        return "zeta";
    }

here's the JS who calls the webmethod:

    $.ajax({
        type: "POST",
        url: 'Catalogo.aspx/checaItem',
        data: "{ id : 'teste' }",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data);
        }
    });

C# Solutions


Solution 1 - C#

You can use:

HttpContext.Current.Session

But it will be null unless you also specify EnableSession=true:

[System.Web.Services.WebMethod(EnableSession = true)]
public static String checaItem(String id)
{ 
    return "zeta";
}

Solution 2 - C#

There are two ways to enable session for a Web Method:

1. [WebMethod(enableSession:true)]

2. [WebMethod(EnableSession = true)]

The first one with constructor argument enableSession:true doesn't work for me. The second one with EnableSession property works.

Solution 3 - C#

For enable session we have to use [WebMethod(enableSession:true)]

[WebMethod(EnableSession=true)]
public string saveName(string name)
{
    List<string> li;
    if (Session["Name"] == null)
    {
        Session["Name"] = name;
        return "Data saved successfully.";

    }
         
    else
    {
        Session["Name"] = Session["Name"] + "," + name;
        return "Data saved successfully.";
    }

  
}

Now to retrive these names using session we can go like this

[WebMethod(EnableSession = true)]
    public List<string> Display()
    {
        List<string> li1 = new List<string>();
        if (Session["Name"] == null)
        {
           
            li1.Add("No record to display");
            return li1;
        }
           
        else
        {
            string[] names = Session["Name"].ToString().Split(',');
            foreach(string s in names)
            {
                li1.Add(s);
            }

            return li1;
        }

    }

so it will retrive all the names from the session and show.

Solution 4 - C#

You can try like this [WebMethod] public static void MyMethod(string ProductID, string Price, string Quantity, string Total)// Add new parameter Here { db_class Connstring = new db_class(); try {

            DataTable dt = (DataTable)HttpContext.Current.Session["aaa"];

            if (dt == null)
            {
                DataTable dtable = new DataTable();

                dtable.Clear();
                dtable.Columns.Add("ProductID");// Add new parameter Here
                dtable.Columns.Add("Price");
                dtable.Columns.Add("Quantity");
                dtable.Columns.Add("Total");
                object[] trow = { ProductID, Price, Quantity, Total };// Add new parameter Here
                dtable.Rows.Add(trow);
                HttpContext.Current.Session["aaa"] = dtable;                   
            }
            else
            {
                object[] trow = { ProductID, Price, Quantity, Total };// Add new parameter Here
                dt.Rows.Add(trow);
                HttpContext.Current.Session["aaa"] = dt;
            }


        }
        catch (Exception)
        {
            throw;
        }
    }

Solution 5 - C#

Take a look at you web.config if session is enabled. This post here might give more ideas. https://stackoverflow.com/a/15711748/314373

Solution 6 - C#

In C#, on code behind page using web method,

[WebMethod(EnableSession = true)]
        public static int checkActiveSession()
        {
            if (HttpContext.Current.Session["USERID"] == null)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }

And, in aspx page,

$.ajax({
                type: "post",
                url: "",  // url here
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{ }',
                crossDomain: true,
                async: false,
                success: function (data) {
                    returnValue = data.d;
                    if (returnValue == 1) {

                    }
                    else {
                        alert("Your session has expired");
                        window.location = "../Default.aspx";
                    }
                },
                error: function (request, status, error) {
                    returnValue = 0;
                }
            });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionS&#233;rgioView Question on Stackoverflow
Solution 1 - C#WraithNathView Answer on Stackoverflow
Solution 2 - C#WarlockView Answer on Stackoverflow
Solution 3 - C#Debendra DashView Answer on Stackoverflow
Solution 4 - C#Md. Didarul IslamView Answer on Stackoverflow
Solution 5 - C#AmalView Answer on Stackoverflow
Solution 6 - C#RamanView Answer on Stackoverflow