使用Session会出错

时间:2016-06-29 10:18:39

标签: c# asp.net session

我有一个aspx页面,我正在调用下面的函数

public static string FunFillEmp(object[] args)
        {

            string StrPriReturn = "";
            DataAccessLayer ObjPriDt = new DataAccessLayer();

            DataTable dt = new DataTable();
            dt = ObjPriDt.ExecuteDataTable("select mkey,Emp_Name,emp_card_no from emp_mst where "+
                                            "department_mkey='" + args[0].ToString() + "' and status in ('A','S') and hub_mkey IN  " +
                                            "(select hub_mkey from emp_mst e,user_mst u where e.mkey=u.employee_mkey and e.STATUS IN ('A','S')   "+
                                            "and u.mkey='" + Session["UserId"].ToString().Trim() + "') " +
                                             "order by 2");
            if (dt.Rows.Count > 0)
            {
                for (int IntpriI = 0; IntpriI < dt.Rows.Count; IntpriI++)
                {
                    StrPriReturn += dt.Rows[IntpriI][0].ToString() + "~" + dt.Rows[IntpriI][1].ToString() + "~" + dt.Rows[IntpriI][2].ToString() + "|";
                }
            }
            return StrPriReturn;
        }

但是使用Session给出了错误

  

非静态字段所需的对象引用

那我怎么在这里使用Session?

2 个答案:

答案 0 :(得分:3)

您需要使用HttpContext.Current.Session["UserId"],因为您在static方法中访问它。

是的,当你没有在Session中分配任何东西时,你需要处理这个场景。

答案 1 :(得分:0)

您的会话未分配,您需要处理该案例:

string UserId = HttpContext.Current.Session["UserId"] == null ? null : HttpContext.Current.Session["UserId"].ToString().Trim();

if(UserId == null)
{
    // do something
}

dt = ObjPriDt.ExecuteDataTable("select mkey,Emp_Name,emp_card_no from emp_mst where " +
                                "department_mkey='" + args[0].ToString() + "' and status in ('A','S') and hub_mkey IN  " +
                                "(select hub_mkey from emp_mst e,user_mst u where e.mkey=u.employee_mkey and e.STATUS IN ('A','S')   " +
                                "and u.mkey='" + UserId + "') " +
                                    "order by 2");