How can I access session in a webmethod?

后端 未结 6 1592
礼貌的吻别
礼貌的吻别 2020-11-29 22:42

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

6条回答
  •  醉酒成梦
    2020-11-29 23:36

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

    [WebMethod(EnableSession=true)]
    public string saveName(string name)
    {
        List 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 Display()
        {
            List li1 = new List();
            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.

提交回复
热议问题