在方法中获取Session变量

时间:2011-10-17 12:29:50

标签: c# asp.net mysql session session-variables

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.Web.Security;
using System.Data;
using System.IO;
using SurelyKnown.Core;
using System.Configuration;
using System.Collections;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Xml;
using System.Windows.Forms;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [System.Web.Services.WebMethod(EnableSession = true)] 
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        int newOrgID = Convert.ToInt32(Session["uOrgID"].ToString());

错误发生在最后一行

 CS0120: An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Session.get'

我该怎么办才能在方法中获取会话值。

2 个答案:

答案 0 :(得分:9)

使用HttpContext.Current.Session

int newOrgID=0;
if(HttpContext.Current.Session["uOrgID"]!=null)
{
  int.TryParse(HttpContext.Current.Session["uOrgID"].ToString(),out newOrgID);
}

答案 1 :(得分:0)

在使用之前检查null,如下所示:

if(Session["uOrgID"] != null)
{
  int newOrgID = Convert.ToInt32(Session["uOrgID"].ToString());
}

您还应该阅读本文,以真正了解如何从Web服务(包括Web和页面方法)访问会话状态:Using ASP.NET Session State in a Web Service