带有静态类的httpcontext,用于存储和检索会话数据

时间:2014-05-07 05:41:43

标签: c# asp.net session httpcontext static-class

我想存储我的全局数据,直到将其插入数据库。所以,我想实现一个可以处理创建和存储会话值的客户类。所以,下面是我的代码。

 public static class SessionHelper
 {
    private static int custCode;
    public static int PropertyCustCode
    {
        get
        {
            return custCode;
        }
        set
        {
            if   (!string.IsNullOrEmpty(HttpContext.Current.Session[propertyCode].ToString()))
            {
                custCode = value;
            }
            else
            {
                throw new Exception("Property Code Not Available");
            }
        }
    }

    public static void MakePropertyCodeSession(int custCode)
    {
        try
        {
            HttpContext.Current.Session[propertyCode] = custCode;
        }
        catch(Exception ex)
        {

        }
    }

我正在从我的网页分配属性代码,如下所示

SessionHelper.MakePropertyCodeSession(7777);

之后我想访问如下的会话值

int propertyCode=SessionHelper.PropertyCustCode;

但是,我无法访问会话值。每一次,我的价值都是null。为什么?我的错在哪里?

1 个答案:

答案 0 :(得分:0)

HttpContext.Current.Session[propertyCode].ToString()

如果 HttpContext.Current.Session[propertyCode] 为空,则会给您带来问题。但是很难看出你想要用什么做代码,也许你应该尝试重写它:

 public static class SessionHelper
 {
  public static int PropertyCustCode
  {
    get
    {
        int result = 0;
        if (int.TryParse(HttpContext.Current.Session[propertyCode], out result){
            return result;
        }
        else
        {
            throw new Exception("HttpContext.Current.Session[propertyCode] is not a integer");
        } 
    }
    set
    {
          HttpContext.Current.Session[propertyCode] = value.ToString();
    }
}

现在你可以这样做:

SessionHelper.PropertyCustCode = 7777;
int custcode = SessionHelper.PropertyCustCode;