0

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

 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价值。为什么?我的错误在哪里?

4

1 回答 1

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;
于 2014-05-07T06:43:13.060 回答