سؤال

I want to store my global data till its inserted into DB. so, i want to implement a customer class which can handle creating and storing session values. So, below is my code.

 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)
        {

        }
    }

I am Assigning Property Code from my webpage like below

SessionHelper.MakePropertyCodeSession(7777);

and after this i want to access session value like below

int propertyCode=SessionHelper.PropertyCustCode;

But, I am not able to access session values. Every time, I am getting as null value. Why? where is my mistake?

هل كانت مفيدة؟

المحلول

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

Will give you problems if the HttpContext.Current.Session[propertyCode] is null. However is it very hard to see what want to do with you code, maybe you should try to rewrite it like:

 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();
    }
}

Now you can just do:

SessionHelper.PropertyCustCode = 7777;
int custcode = SessionHelper.PropertyCustCode;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top