//這裡cookie怎麼寫,還要加密
| 代碼如下 |
複製代碼 |
Respone.Cookie.Add(new Cookie("User_Name",(加密)txtUserName.text)); public void CheckLogin() { 先判斷是否有Session if(Session["User_Name"]==null || Session["User_Name"]=="") { 再判斷是否有Cookie if(Request.Cookie["User_Name"]!=null &&Request.Cookie["User_Name"]!="") { Session["User_Name"] = (解密)Request.Cookie["User_Name"]; } else { //即沒Sessoin,又沒Cookie 轉到登入頁 Response.ReDriect("Login.aspx") } } } |
Cookies在ASP中的最常用的方法,
1.如何寫入Cookies?
Response.Cookies("欄位名")=變數或字串,例如:
Response.Cookies("name2")="Dingdang"
2.如何設定Cookies時間?
Response.Cookies("欄位名").expires=時間函數+N,例如:
Response.Cookies("name2").expires=date+1,表示Cookies儲存1天,再比如:
Response.Cookies("name2").expires=Hour+8,表示Cookies儲存8小時。
3.在以往的ASP教程中,很少有介紹Cookies退出的方法。在“退出”這個ASP頁中可以這樣寫:
Response.Cookies("欄位名")=""
之後,在用戶端的瀏覽器就清除了Cookies,並且Cookies檔案會消失。注意有多少個欄位,就要寫多少句來清除。
4.如何讀取Cookies?
變數名=Request.Cookies("欄位名"),例如:
name2=Request.Cookies("name2")
如果網頁中寫入這句,則會顯示“Dingdang”。
也可以這樣直接讀取Cookies,
Cookies是屬於Session對象的一種。但有不同,Cookies不會佔伺服器資源;而“Session”則會佔用伺服器資源。所以,盡量不要使用Session,而使用Cookies
執行個體
HttpWebRequest 發送 POST 請求到一個網頁伺服器實現自動使用者登入
假如某個頁面有個如下的表單(Form):
| 代碼如下 |
複製代碼 |
<form name="form1" action="http:www.breakn.com/login.asp" method="post"> <input type="text" name="userid" value=""> <input type="password" name="password" value=""> </form>
|
從表單可看到表單有兩個表單域,一個是userid另一個是password,所以以POST形式提交的資料應該包含有這兩項。
其中POST的資料格式為:
表單網域名稱稱1=值1&表單網域名稱稱2=值2&表單網域名稱稱3=值3……
要注意的是“值”必須是經過HTMLEncode的,即不能包含“<>=&”這些符號。
本例子要提交的資料應該是:
| 代碼如下 |
複製代碼 |
userid=value1&password=value2 string strId = "guest"; string strPassword= "123456"; ASCIIEncoding encoding=new ASCIIEncoding(); string postData="userid="+strId; postData += ("&password="+strPassword); byte[] data = encoding.GetBytes(postData); // Prepare web request... HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http:www.here.com/login.asp"); myRequest.Method = "POST"; myRequest.ContentType="application/x-www-form-urlencoded"; myRequest.ContentLength = data.Length; Stream newStream=myRequest.GetRequestStream(); // Send the data. newStream.Write(data,0,data.Length); newStream.Close(); // Get response HttpWebResponse myResponse=(HttpWebResponse)myRequest.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.Default); string content = reader.ReadToEnd(); Console.WriteLine(content); |