Reputation: 5790
I am developing asp.net web application in which i am using Session
to store user related data.Though i am storing data in session object when i am trying to retrieve it gives me error :
Object reference not set to an instance of an object.
Setting session variable
somewhere in code behind of aspx page (myfile.aspx.cs)
HttpContext.Current.Session["ProjectID"] = Request.QueryString["Pid"].ToString();
Retrieving Session Variable
Normal Business Logic C# Class (Someclass.cs)
sProjectID = HttpContext.Current.Session["ProjectID"].ToString();
It gives me error on above line. It looks weird to me. can anyone explain this ?
Edit:
Call to class pass through generic handler (.ashx) page
Upvotes: 2
Views: 16937
Reputation: 15893
If it is really the line of code you showed, that produces exception, it means your "Normal Business Logic" is running in a non-HttpRequest handling thread, where thing such as Context and Session are not available. Check that HttpContext.Current
and HttpContext.Current.Session
are not null.
Update:
After seeing your edit - to have access to Session, your handler must include IRequiresSessionState
in its class declaration. See: HttpContext.Current.Session is null in Ashx file.
Upvotes: 2
Reputation: 12569
Try setting the cookie this way:
HttpCookie cookie = HttpContext.Current.Request.QueryString["Pid"].ToString();
cookie.Expires = DateTime.Now.AddDays(7); // Set the expiration duration
HttpContext.Current.Response.Cookies.Set(cookie); // Set it to the response
And try getting the cookie this way on the next request:
string value = HttpContext.Current.Request.Cookies["Pid"] != null ? this.Page.Request.Cookies["Pid"].ToString() : null; // load it from request
Honestly, you should not try to receive your cookie in your business logic at all, as it has nothing to do with your website. Instead you should load the cookie in the UI (web) and pass the value as parameter to any function or property of your Someclass.cs in your business logic.
Take a look at the N-tier model and it's reasons to do so.
Upvotes: 0
Reputation: 269
You can't find any value in the session in the Debug mode.. Assign it to a reference variable like string and find whether it is returning a value..
and for a good practice check the session variable is null or not before assigning to any object..
Upvotes: 0
Reputation: 152
Can you reach in the debug mode line where you setting session values? If you can try to hit line after and inspect value in session by the key "ProjectID".
Upvotes: 0