views:

26

answers:

2

in my pageload i have got the session["name"]

When i use this code to save:

Stream stream = null;
request = (HttpWebRequest)WebRequest.Create(url);
response = (HttpWebResponse)request.GetResponse();

When it comes to this line:

response = (HttpWebResponse)request.GetResponse();

it again move on to the pageload and that time the session is null. how??? how to maintain the session in the same page. why it is cleared when this line encounters...

A: 

You are trying to make the Web Request from your application and right there it is not your session, but your application session.

The data (name key and it's value) is stored in your session, but when you call WebRequest.GetResponse() method then your application starts it's own, brand new session.

ŁukaszW.pl
+1  A: 

The reason that sessions don't persist with HttpWebResponse is because by default, HttpWebResponse will not handle cookies for you. ASP.NET uses a cookie to identify which session belongs to a user.

Thankfully, there's a helper class called CookieContainer that can help you with this. Create a CookieContainer and attach it to your web request - on subsequent requests, you will need to attach the cookie container, or the cookies within it to the request again to persist session:

CookieContainer cookieJar = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
request.CookieContainer = cookieJar;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// on a second request, you can use the cookieJar container to pass the session cookie.
Ryan Brunner
If you are allowing cookieless sessions (Cookieless="true" in your web config file), then you can simulate a cookieless session by including the session cookie in the URL. By default, I think HttpWebRequest will indicate that it supports cookies, which means ASP.NET will not attempt to initiate a cookieless session for you.
Ryan Brunner