登錄頁面
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
//1.判斷用戶名密碼是否正確,2.給服務器寫cookie 存用戶名但是不存密碼
if (txtloginId.Text != "")
{
HttpCookie user = new HttpCookie("user");
user["name"] = txtloginId.Text;
user.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(user);//寫到Respon中,由他寫入瀏覽器
//2.存登錄時間
HttpCookie loginTime = new HttpCookie("time");
loginTime["lastTime"] = DateTime.Now.ToShortDateString();
user.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(loginTime);
//3.跳轉頁面
Response.Redirect("Main.aspx");
}
}
}
(登錄頁面沒有問題)
主頁面
(還包含發送消息和展示消息,此處主要接收用戶名和登錄時間)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Main : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie user = Request.Cookies["user"];
if (user != null)
{
String name = user["name"];
lblLoginDate.Text = name + " welcome ";
}
HttpCookie loginTime = Request.Cookies["time"];
if (loginTime != null)
{
String time = loginTime["lastTime"];
lblLoginDate.Text = lblLoginDate.Text +"login time"+ time;
}
}
}
發送消息
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class SendMessage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSendMessage_Click(object sender, EventArgs e)
{
HttpCookie user = Request.Cookies["user"];
if (user != null)
{
string name = user["name"].ToString() ;
string mess = txtMessage.Text.ToString();
Application.Lock();
Application["name"]= name;
Application["mess"] = mess;
Application.UnLock();
}
}
}
展示消息
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class ShowMessage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Application.Lock();//一定要寫
string name = Application["name"].ToString();
string mess = Application["mess"].ToString();
Application.UnLock();
txtShowMessage.Text += name + "說:" + mess+"\n";
}
}
剛開始沒寫Lock和UnLock,一直報錯“未將對象引用設置到對象的實例”,搜半天都說是取不到值,沒改好突然想到Lock和UnLock,加上之後消息可以顯示了但是需要刷新而且只顯示最新一條