如何在同一页面保持session

发布于 2024-09-13 20:44:44 字数 354 浏览 10 评论 0原文

在我的页面加载中,我得到了会话[“name”]

当我使用此代码保存时:

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

当涉及到这一行时:

response = (HttpWebResponse)request.GetResponse();

它再次移至页面加载,此时会话为空。如何???如何在同一页面保持会话。为什么当这一行遇到...时它被清除

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...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凉宸 2024-09-20 20:44:44

会话不通过 HttpWebResponse 持续存在的原因是,默认情况下,HttpWebResponse 不会为您处理 cookie。 ASP.NET 使用 cookie 来识别哪个会话属于用户。

值得庆幸的是,有一个名为 CookieContainer 的帮助器类可以帮助您完成此任务。创建一个 CookieContainer 并将其附加到您的 Web 请求 - 在后续请求中,您将需要将 Cookie 容器或其中的 Cookie 再次附加到请求以保留会话:

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.

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.
鱼窥荷 2024-09-20 20:44:44

您尝试从您的应用程序发出 Web 请求,但它不是您的会话,而是您的应用程序会话。

数据(名称键及其值)存储在您的会话中,但是当您调用 WebRequest.GetResponse() 方法时,您的应用程序将启动它自己的全新会话。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文