【问题标题】:httpcontext with static class to store and retrieve session data带有静态类的 httpcontext 来存储和检索会话数据
【发布时间】:2014-05-07 05:41:42
【问题描述】:

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

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

【问题讨论】:

  • propertyCode 来自哪里?
  • 我通过在加载自身时调用此 MakePpertyCodeSession 方法从我的网页分配此属性代码,此后我想通过使用其属性 (PropertyCustCode) 在整个应用程序中使用此会话值。希望,很清楚
  • 尝试在使用静态类的地方添加重要的代码 sn-p
  • 我已经更新了我的代码 sn-p。请立即查看。
  • 也许我需要休息一下,但你的项目可以编译?

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


【解决方案1】:
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-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    相关资源
    最近更新 更多