如何在webmethod中访问会话(session)?

95

我能在WebMethod中使用会话值吗?

我尝试过使用System.Web.Services.WebMethod(EnableSession = true),但我无法像这个例子中的那样访问Session参数:

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

这里是调用Web方法的JavaScript代码:

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

4
提供代码示例会帮助我们为您提供答案。 - volpav
你是否收到异常? - Darin Dimitrov
1
在上面的例子中,我没有看到您尝试访问任何会话值。您需要首先设置会话变量,然后像您发布的链接那样访问它。返回(int)Session [“Conversions”]; - capdragon
+1 我从这个页面得到了解决方案。 - 4b0
@BrainSlugs83 WebMethods绝对不必须是静态的,Session不起作用与方法是否静态无关。Session["key"]是Page.Session ["key"]的简写。这里没有Page存在,因为该类是从WebService类派生的,而不是从aspx页面派生的Page类。 - Jason Kelley
显示剩余2条评论
6个回答

132
你可以使用:

HttpContext.Current.Session

但是它将会是null,除非你也指定了EnableSession=true

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

18
具有讽刺意味的是,我已经在做这件事情了——只是它对我没有起作用。HttpContext.Current.Session.Count返回的是0(即Session中没有任何项)。对我而言,答案就在问题中,将[WebMethod]更改为[WebMethod(EnableSession = true)]就可以了。哇! - BrainSlugs83
4
请记得配置 web.config 文件:<sessionState mode="InProc"/>。该设置用于定义 ASP.NET 应用程序的会话状态模式,应将其放置在 web.config 文件中以确保正确的功能。 - Moesio

10

启用 Web 方法的会话有两种方法:

1. [WebMethod(enableSession:true)]

2. [WebMethod(EnableSession = true)]

使用构造函数参数 enableSession:true 的第一个选项对我无效。带有 EnableSession 属性的第二个选项有效。


我无法弄清楚第一个是否可以编译 - 我相信它不能。第二个可以工作,因为你正在设置属性(这里显而易见XD)。 - MVCDS
@MVCDS 为什么你认为它不应该被编译?在文档中可以找到一个公共构造函数 WebMethodAttribute(Boolean) - Warlock
你说得完全正确。如果不设置参数名称,它会表现出不同的行为吗?因为如果是这样的话,在编写属性构造函数时可能会发生非常奇怪的事情。 - MVCDS
在Visual Studio 2022中,.Net Framework 4对我来说无法工作。 - John Foll

1
为了启用会话,我们需要使用 [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.";
    }


}

现在我们可以通过会话来检索这些名称,做法如下:
[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;
        }

    }

所以它将从会话中检索所有名称并显示。

0
你可以尝试这样做: [WebMethod] public static void MyMethod(string ProductID, string Price, string Quantity, string Total)// 在此处添加新参数 { 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

0

在C#中,使用代码后台页面的Web方法:

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

而且,在aspx页面中,

$.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;
                }
            });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接