95

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);
        }
    });
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
Sérgio
  • 1,597
  • 2
  • 12
  • 16
  • 4
    Posting a code example will help us provide you with an answer. – volpav Jan 21 '11 at 12:09
  • Are you getting an exception? – Darin Dimitrov Jan 21 '11 at 13:55
  • 1
    In the example above i don't see you trying to access any session values. You need to set the session var first then access it like the link you posted. return (int) Session["Conversions"]; – capdragon Jan 21 '11 at 13:59
  • @volpav he provided example code. – BrainSlugs83 Oct 16 '12 at 00:26
  • No, @capdragon the Page's Session property doesn't exist for static methods (WebMethods are required to be static) -- he's asking where to find the property -- as posted below, it lives in the current HttpContext. – BrainSlugs83 Oct 16 '12 at 00:27
  • +1 I got soln from this page. – 4b0 Dec 02 '12 at 12:22
  • @BrainSlugs83 WebMethods definitely do not have to be static and Session not working has nothing to do with the method being static. Session["key"] is shorthand for Page.Session["key"]. Page doesn't exist here because the class is derived from the WebService class instead of the Page class that aspx pages are derived from. – Jason Kelley Jul 25 '13 at 21:07

6 Answers6

131

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";
}
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
WraithNath
  • 17,658
  • 10
  • 55
  • 82
  • 18
    Ironically, this is what I was already doing -- only it wasn't working for me. HttpContext.Current.Session.Count was returning 0 (i.e. no items in Session). For me, the answer was in the question, changing [WebMethod] to [WebMethod(EnableSession = true)] worked. Woot! – BrainSlugs83 Oct 16 '12 at 00:28
  • 4
    Remember to config web.config – Moesio Aug 21 '14 at 19:54
10

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.

Warlock
  • 7,321
  • 10
  • 55
  • 75
  • I cannot [figure out](https://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute%28v=vs.110%29.aspx) if the first one even compiles - I'd belive it doesn't. The second does work because you are setting the property (just being obvious here XD). – MVCDS Mar 02 '15 at 12:45
  • @MVCDS Why do you think that it should not be compiled? You can find a public constructor `WebMethodAttribute(Boolean)` in docs. – Warlock Mar 03 '15 at 07:07
  • You're absolutely right. Does it behaves differently if you don't set the parameter name? Because if it does, something very weird happened when they were coding constructors (for attributes). – MVCDS Mar 03 '15 at 15:45
  • This is not working for me in Visual Studio 2022 for .Net Framework 4. – John Foll Apr 03 '23 at 18:08
1

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.

Debendra Dash
  • 5,334
  • 46
  • 38
0

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;
        }
    }
0

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

Community
  • 1
  • 1
Amal
  • 461
  • 5
  • 17
0

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;
                }
            });
Raman
  • 1
  • 1