我已经阅读了很多有关该主题的文章,但找不到解决方案。 因此,请不要将此问题标记为重复,因为其他解决方案不起作用并且已经过时。
我有一个 Web 应用程序,其页面包含 GridView(每行一个按钮)。 该按钮将创建一个 HttpWebRequest(或 WebClient,它是相同的)并获取其 html。
我尝试使用一个 cookie 或所有 cookie,但没有成功。 这是代码:
String path = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/");
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(path + "MyPage.aspx");
CookieContainer cookieContainer = new CookieContainer();
HttpCookie httpCookie = HttpContext.Current.Request.Cookies.Get("ASP.NET_SessionId");
if (httpCookie != null)
{
Cookie myCookie = new Cookie();
// Convert between the System.Net.Cookie to a System.Web.HttpCookie...
myCookie.Domain = webRequest.RequestUri.Host;
myCookie.Expires = httpCookie.Expires;
myCookie.Name = httpCookie.Name;
myCookie.Path = httpCookie.Path;
myCookie.Secure = httpCookie.Secure;
myCookie.Value = httpCookie.Value;
cookieContainer.Add(myCookie);
}
webRequest.CookieContainer = cookieContainer;
string responseHTML = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
responseHTML = responseReader.ReadToEnd();
}
}
}
webRequest.GetResponse
将超时。
我认为问题在于域(localhost),我知道这是不可能的,但我没有任何域,我不会在 web.config 中创建一个假域。此外,我尝试使用假域名但没有成功。
没有以下行
webRequest.CookieContainer = cookieContainer;
无需共享 session 即可正常工作。 我记得必须设置域,否则我将收到相对错误。
最佳答案
session 访问必须序列化。当您使用 ASP.NET session 时,有必要“序列化”HTTP 请求以避免线程问题。如果并行处理两个或多个请求,则意味着两个线程可以同时更改或读取 session 变量,这可能会导致各种问题。
好消息:ASP.NET will serialize the requests for you, automatically 。如果您使用相同的 ASP.NET_SessionId 发送第二个请求,它将等待第一个请求完成。
坏消息:这意味着您正在尝试的机制将不起作用。您的 Web 请求在一个已在进行中的 HTTP 请求的上下文中运行;它将阻止任何其他 HTTP 请求,直到完成为止,包括您通过 WebRequest 发送的请求。
更多好消息:如果您的页面读取 session 数据但不写入它,它可以指定一个提示,允许两个线程同时运行。尝试将其添加到两个页面(您的代码所在的页面和您的代码尝试访问的页面):
<% @Page EnableSessionState="ReadOnly" %>
如果 ASP.NET 识别出 session 需求是只读的,它将允许两个只读线程使用相同的 session ID 同时运行。
如果您需要在任一页面中进行读/写访问,那么您就不走运了。
替代方案是使用 HttpServerUtility.Transfer反而。第一页的角色将会改变。它将控制权交给第二页,而不是充当第二页的代理。通过将页面串联起来,您可以避免任何并行问题。
示例:
Server.Transfer("MyPage.aspx");
关于c# - 在新的 HttpWebRequest 上共享当前 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43189844/