我登录B系统后,在B系统中模拟登录A系统,这时在A系统我会被用户名放入SESSION或COOKIE当中。这样A系统就登录了。
但是我这样做后,登录时是登录成功了,可进入A系统的其它页面时,Session及Cookie就读不出来值了。请问为什么?应如何解决?
A系统前台代码<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="WebUI._Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>title</title>
<style type="text/css">
.style1
{
width: 26%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center" border="0" cellpadding="0" cellspacing="0" width="20%">
<tr>
<td class="style1">
<div align="left">
<font style="height: 1; font-size: 9pt; color: #bfdbeb; filter: glow(color=#1070a3,strength=1)">
username:
</font>
</div>
</td>
<td height="25" width="79%">
<div align="left">
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
</div>
</td>
</tr>
<tr>
<td align="left" class="style1">
<div align="left">
<font style="height: 1; font-size: 9pt; color: #bfdbeb; filter: glow(color=#1070a3,strength=1)">
password:
</font>
</div>
</td>
<td height="25">
<div align="left">
<asp:TextBox ID="PassWord" runat="server"></asp:TextBox>
</div>
</td>
</tr>
<tr>
<td align="left" class="style1">
</td>
<td height="25">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</td>
</tr>
</table>
<br />
</div>
</form>
</body>
</html>A系统后台代码using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using BLL;namespace WebUI
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ } //protected void Button1_Click(object sender, EventArgs e)
//{
// string username = UserName.Text;
// string password = PassWord.Text;
// Response.Redirect("WebForm2.aspx?username="+username+"&password="+password+"");
//} protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("zzzzzzzzzzzzzz<br>");
if (UserName.Text.Trim().Equals(string.Empty) || PassWord.Text.Trim().Equals(string.Empty))
{
//MsgLabel.Text = "用户名、密码不能为空!";
Response.Write("error!");
}
else
{
Response.Write("suc!");
HttpCookie cookie = new HttpCookie("username", UserName.Text.Trim());
// cookie.Domain = "Dc1.Com";
Response.Cookies.Add(cookie); HttpCookie c = Request.Cookies["username"];
Response.Write(c.Value + "<BR>"); Response.Redirect("Main.aspx");
// Session["admin_name"] = this.UserName.Text;
//LoginInfo li = new LoginInfo();
//int result = 0;
//result = li.UserIsExists(this.UserName.Text.Trim(), this.PassWord.Text.Trim());
//if (result > 0)
//{
// Session["admin_name"] = this.UserName.Text;
// MsgLabel.Text = string.Empty;
// //Response.Redirect("WebForm2.aspx");
// Response.Write("登录成功");
//}
//else
//{
// MsgLabel.Text = "用户名密码错误或用户不存在!";
// return;
//} }
}
}
}B系统模拟登录时的代码 //模拟提交
private void MoNiLogin()
{
//地址及参数
string postDate = string.Format("UserName={0}&PassWord={1}&Button1={2}&__EVENTVALIDATION={3}&__VIEWSTATE={4}", "admin", "admin", "Button", "/wEWBAL5vI2NAQKvruq2CAKyxeCRDwKM54rGBjWcqdHACXyCvqJDUwLJr4uEZzjq", "/wEPDwULLTExNTc2NTI3OTlkZLOL2o9SYsLVldoHpEyGbkI5xtXT");
byte[] data = System.Text.Encoding.GetEncoding("GB2312").GetBytes(postDate);
string postUrl = @"http://192.168.1.222:812/Login.aspx"; //准备请求
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(postUrl);
try
{
req.Method = "Post";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length; Stream stream = req.GetRequestStream();
//发送数据
stream.Write(data, 0, data.Length);
stream.Close();
HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
Stream receiveStream = rep.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
StreamReader readStream = new StreamReader(receiveStream, encode); Char[] read = new Char[256];
int count = readStream.Read(read, 0, 256);
StringBuilder sb = new StringBuilder();
while (count > 0)
{
string readstr = new string(read, 0, count);
sb.Append(readstr);
count = readStream.Read(read, 0, 256);
}
rep.Close();
readStream.Close();
Response.Write(sb.ToString()); Response.Write("Login success!");
//return true;
// this.lbtnLink.Visible = true;
// Response.Redirect("http://192.168.1.222:812/Main.aspx");
}
catch (Exception ex)
{ //throw;
Response.Write("Login error:" + ex.Message.ToString());
//return false;
} }
但是我这样做后,登录时是登录成功了,可进入A系统的其它页面时,Session及Cookie就读不出来值了。请问为什么?应如何解决?
A系统前台代码<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="WebUI._Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>title</title>
<style type="text/css">
.style1
{
width: 26%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center" border="0" cellpadding="0" cellspacing="0" width="20%">
<tr>
<td class="style1">
<div align="left">
<font style="height: 1; font-size: 9pt; color: #bfdbeb; filter: glow(color=#1070a3,strength=1)">
username:
</font>
</div>
</td>
<td height="25" width="79%">
<div align="left">
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
</div>
</td>
</tr>
<tr>
<td align="left" class="style1">
<div align="left">
<font style="height: 1; font-size: 9pt; color: #bfdbeb; filter: glow(color=#1070a3,strength=1)">
password:
</font>
</div>
</td>
<td height="25">
<div align="left">
<asp:TextBox ID="PassWord" runat="server"></asp:TextBox>
</div>
</td>
</tr>
<tr>
<td align="left" class="style1">
</td>
<td height="25">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</td>
</tr>
</table>
<br />
</div>
</form>
</body>
</html>A系统后台代码using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using BLL;namespace WebUI
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ } //protected void Button1_Click(object sender, EventArgs e)
//{
// string username = UserName.Text;
// string password = PassWord.Text;
// Response.Redirect("WebForm2.aspx?username="+username+"&password="+password+"");
//} protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("zzzzzzzzzzzzzz<br>");
if (UserName.Text.Trim().Equals(string.Empty) || PassWord.Text.Trim().Equals(string.Empty))
{
//MsgLabel.Text = "用户名、密码不能为空!";
Response.Write("error!");
}
else
{
Response.Write("suc!");
HttpCookie cookie = new HttpCookie("username", UserName.Text.Trim());
// cookie.Domain = "Dc1.Com";
Response.Cookies.Add(cookie); HttpCookie c = Request.Cookies["username"];
Response.Write(c.Value + "<BR>"); Response.Redirect("Main.aspx");
// Session["admin_name"] = this.UserName.Text;
//LoginInfo li = new LoginInfo();
//int result = 0;
//result = li.UserIsExists(this.UserName.Text.Trim(), this.PassWord.Text.Trim());
//if (result > 0)
//{
// Session["admin_name"] = this.UserName.Text;
// MsgLabel.Text = string.Empty;
// //Response.Redirect("WebForm2.aspx");
// Response.Write("登录成功");
//}
//else
//{
// MsgLabel.Text = "用户名密码错误或用户不存在!";
// return;
//} }
}
}
}B系统模拟登录时的代码 //模拟提交
private void MoNiLogin()
{
//地址及参数
string postDate = string.Format("UserName={0}&PassWord={1}&Button1={2}&__EVENTVALIDATION={3}&__VIEWSTATE={4}", "admin", "admin", "Button", "/wEWBAL5vI2NAQKvruq2CAKyxeCRDwKM54rGBjWcqdHACXyCvqJDUwLJr4uEZzjq", "/wEPDwULLTExNTc2NTI3OTlkZLOL2o9SYsLVldoHpEyGbkI5xtXT");
byte[] data = System.Text.Encoding.GetEncoding("GB2312").GetBytes(postDate);
string postUrl = @"http://192.168.1.222:812/Login.aspx"; //准备请求
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(postUrl);
try
{
req.Method = "Post";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length; Stream stream = req.GetRequestStream();
//发送数据
stream.Write(data, 0, data.Length);
stream.Close();
HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
Stream receiveStream = rep.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
StreamReader readStream = new StreamReader(receiveStream, encode); Char[] read = new Char[256];
int count = readStream.Read(read, 0, 256);
StringBuilder sb = new StringBuilder();
while (count > 0)
{
string readstr = new string(read, 0, count);
sb.Append(readstr);
count = readStream.Read(read, 0, 256);
}
rep.Close();
readStream.Close();
Response.Write(sb.ToString()); Response.Write("Login success!");
//return true;
// this.lbtnLink.Visible = true;
// Response.Redirect("http://192.168.1.222:812/Main.aspx");
}
catch (Exception ex)
{ //throw;
Response.Write("Login error:" + ex.Message.ToString());
//return false;
} }
string resultPost = string.Empty;
try
{
CookieContainer cookieContainer = new CookieContainer(); HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(Url); request.Method = "POST";
request.ContentType = "text/xml";
request.CookieContainer = cookieContainer; request.KeepAlive = true;
request.ProtocolVersion = HttpVersion.Version11;
request.Credentials = CredentialCache.DefaultCredentials;
request.CookieContainer = cookieContainer;
request.Accept = "*/*";
request.Headers.Add("Accept-Encoding", "gzip, deflate");
request.Headers.Add("Accept-Language", "zh-cn");
request.Headers.Add("UA-CPU", "x86");
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; MAXTHON 2.0)";
byte[] buffer1 = Encoding.GetEncoding("utf-8").GetBytes(this.XmlDoc.OuterXml);
request.ContentLength = buffer1.Length;
Stream stream1 = request.GetRequestStream();
stream1.Write(buffer1, 0, buffer1.Length);
stream1.Close(); HttpWebResponse res = (HttpWebResponse)request.GetResponse(); if (!string.IsNullOrEmpty(res.Headers[System.Net.HttpResponseHeader.SetCookie]))
{
string s = res.Headers[System.Net.HttpResponseHeader.SetCookie];
MatchCollection M = new Regex("(.*?)=(.*?)path=(.*?),", RegexOptions.IgnoreCase).Matches(s + ","); foreach (Match m in M)
{
HttpCookie hc = TopWinCMS.OpenAPI.Passport.PassportHelper.GetCookieFromString(m.Groups[0].Value.TrimEnd(','));
if (hc != null)
HttpContext.Current.Response.Cookies.Add(hc);
}
}
Stream stream2 = res.GetResponseStream();
StreamReader reader1 = new StreamReader(stream2, Encoding.UTF8);
resultPost = reader1.ReadToEnd(); reader1.Close();
}
catch (Exception ex)
{
AddErrStr(ex.Message);
return;
} #region 从字符串生成Cookie
/// <summary>
/// 从字符串生成Cookie
/// </summary>
/// <param name="CookieString"></param>
/// <returns></returns>
public static HttpCookie GetCookieFromString(string CookieString)
{
//test=TestDateTime=2008-11-26 23:34:19&A=qqqqq&B=wwwww; domain=localhost; expires=Thu, 27-Nov-2008 15:34:19 GMT; path=/
string CookieName = CookieString.Split('=')[0];
string CookiePropertys = CookieString.Substring(CookieString.IndexOf('=') + 1);
string[] Propertys = Regex.Split(CookiePropertys, "; ");
HttpCookie hc = new HttpCookie(CookieName); foreach (string p in Propertys)
{
string[] Property = p.Split('=');
if (Property.Length == 1)
{
if (Property[0] == "httponly")
hc.HttpOnly = true;
}
else if (Property.Length > 2)//处理Cookie 的值
{
foreach (string PropertyValue in Propertys[0].Split('&'))
{
string[] Values = PropertyValue.Split('=');
hc.Values[Values[0]] = Values[1];
}
}
else
{
if (Property[0] == "domain")
{
hc.Domain = Property[1];
}
else if (Property[0] == "expires")
{
//hc.Expires = Convert.ToDateTime(Property[1]);
}
else if (Property[0] == "path")
{
hc.Path = Property[1];
}
else if (Property[0] == "secure")
{
hc.Secure = bool.Parse(Property[1]);
}
else//处理Cookie 的值
{
string[] Values = Property[1].Split('&');
if (Values.Length > 1)
{
hc.Values[Values[0]] = Values[1];
}
else
{
hc.Values[Property[0]] = Property[1];
}
}
}
}
return hc;
}
#endregion
请问:这段代码是做什么用的?
if (!string.IsNullOrEmpty(res.Headers[System.Net.HttpResponseHeader.SetCookie]))
{
string s = res.Headers[System.Net.HttpResponseHeader.SetCookie];
MatchCollection M = new Regex("(.*?)=(.*?)path=(.*?),", RegexOptions.IgnoreCase).Matches(s + ","); foreach (Match m in M)
{
HttpCookie hc = TopWinCMS.OpenAPI.Passport.PassportHelper.GetCookieFromString(m.Groups[0].Value.TrimEnd(','));
if (hc != null)
HttpContext.Current.Response.Cookies.Add(hc);
}
}
request.CookieContainer= cookieContainer; 还是出现Cookie及Session取不出的问题。
我的情况是这样的:
B系统为我的当前系统
A系统是我的模拟登录的系统当我模拟登录A系统后,我登录成功了,成功后我会把我登录的用户名存入我的Cookie或Session当中。
存储成功。
这时的效果应该是A系统已经登录成功了的。
但这时我的页面还在B系统当中。
当我点击B系统,进入A系统的一个验证session及cookie的页面中。A系统会提示我,之存储的session及cookie为空。请问这是什么原因?应该如何解决呢?
你也说了你登录成功后的页面是在B系统中,所以A系统中怎么可能会有session跟cookie的值呢,你要把这两个值从B系统中带到A系统中,然后在A系统对于session跟cookie赋值以后A系统中才有这两个值呀
但此时,当前的URL地址还是在B系统中。 那,我的COOKIE到底存储到了哪里?
还有,B系统模拟登录至A系统的login.aspx页,此时,A系统做验证,验证成功后,会把用户名存入Cookie当中。存储成功后,会Response.Redirect到我的Validate.aspx,来验证Cookie是否为空。 我的验证结果是,成功,Cookie中取出存储进去的用户名。
但此时,当前的URL地址还是在B系统中。 那,我的COOKIE到底存储到了哪里?
以上的情况,URL地址都是在B系统。
这时,我在B系统点击链接,链接到A系统的Validate.aspx页面进行验证,这时,验证失败…Cookie里没东西…
Response.Cookies("domain").Value = DateTime.Now.ToString
Response.Cookies("domain").Expires = DateTime.Now.AddDays(1)
Response.Cookies("domain").Domain = "contoso.com"
这样,该Cookie就可用于主域、sales.contoso.com 和 support.contoso.com
具体可以这样做,,
修改web.config
<sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="true" timeout="30" />启动 stateSever服务,,,在给实体类加序列化,,就OK了,,
二楼是构造一个CookieContainer并将其发送到了本地的IE的Cookie中,这个是没错的至于Session
Session是默认依赖于Cookie的(如果你不设置CookieLess =true),它会造构一个ID,然后与本地的Cookie相匹配,表示这是一个持续的访问,但是二个IE窗口,他们的SessionID也是不同的(也有可能相同),但是,你这种肯定是不同的.
问题就很简单的了.如果你是使用的Form验证,你只需要写相应的Cookie就可以了,保证其Key值一致如果你是使用的Session验证,那么.这个问题就复杂了.可能你另外开一个IE窗口,再去访问,它可能不是通过通验证的,那么通过验证的在哪里呢?httprequest中.对于httprequest我也不是很熟,
不知道他会不会持续的保存与Session对应的Cookie不知道说了一大堆你听懂没有
至于如何保存Session的内容,保存到那里,与你的验证过程是无关的,这个不需要关心
\如果你现在使用的www.abc.com的域
而你要输出www.bcd.com的域 使用 Response.Cookies("domain").Domain = "www.bcd.com" 负责任的告诉你,这种是不充许,你可以使用相关工具看一下,是无反应的.最好还是使用二楼的做法
当然了,你输出
Response.Cookies("domain").Domain = "abc.com"
Response.Cookies("domain").Domain = "www.abc.com"
都是可以的
现在问题更简单了,你只要解决Cookie的问题,Session是一致的,无论是IE(8)还是firefox(3.5)中都可以取到Session值
Cookie与Session丢失。