我已经阅读了许多关于该主题的文章,但找不到解决方案。 因此,请不要将此问题标记为重复,因为其他解决方案无法正常工作并且已经过时。在新的HttpWebRequest上共享当前会话
我有一个包含GridView的页面(每行一个按钮)的Web应用程序。 该按钮将创建一个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;
它很好地工作,而不共享会话。 我记得域必须设置,否则我会收到相对错误。
很好的解决方案,但我需要在会话来写。第一页写道,第二页读。否则,我会使用查询字符串。该程序很旧,所以我试图不编辑一些页面。其他想法? @John Wu – Emanuele
是的,[this](https://msdn.microsoft.com/en-us/library/caxa892w(v = vs.110).aspx)。 –
我的代码在哪里? – Emanuele