how to maintain the session in the same page
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开发者_StackOverflow中文版 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...
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.
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.
精彩评论