【问题标题】:Get Session variable inside a method在方法中获取会话变量
【发布时间】:2011-12-09 06:35:43
【问题描述】:
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'

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

【问题讨论】:

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


【解决方案1】:

使用HttpContext.Current.Session

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

【讨论】:

  • @Mark - Session 是页面属性,不能在 Page 类之外或静态方法中使用,因此您可以通过 HttpContext.Current.Session 方法从上下文中获取 Session 对象的引用。跨度>
【解决方案2】:

在使用前检查是否为 null,如下所示:

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

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

【讨论】:

  • 这实际上不是一个好习惯。 Session["uOrgID"] 可以在你有机会解析它之前被删除。你应该做 string uOrgID = Session["uOrgID"] as string; if(!string.IsNullOrEmpty(uOrgID)) ....
猜你喜欢
  • 1970-01-01
  • 2011-02-04
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 2010-09-25
  • 1970-01-01
  • 2014-05-25
相关资源
最近更新 更多