如何在web方法中访问会话?

Sér*_*gio 82 c# session

我可以在一个内部使用会话值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";
    }
Run Code Online (Sandbox Code Playgroud)

这是调用web方法的JS:

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

Wra*_*ath 112

您可以使用:

HttpContext.Current.Session
Run Code Online (Sandbox Code Playgroud)

null除非你还指明EnableSession=true:

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

  • 具有讽刺意味的是,这就是我已经在做的事情 - 只是它不适合我.HttpContext.Current.Session.Count返回0(即Session中没有项目).对我来说,答案就是问题,将[WebMethod]改为[WebMethod(EnableSession = true)].活泉! (18认同)
  • 请记住配置web.config <sessionState mode ="InProc"/> (4认同)

War*_*ock 10

有两种方法可以为Web方法启用会话:

1. [WebMethod(enableSession:true)]

2. [WebMethod(EnableSession = true)]
Run Code Online (Sandbox Code Playgroud)

带构造函数参数的第一个enableSession:true对我不起作用.第二个EnableSession有财产的人.