Ngôn ngữ ASP.NET - Đối tượng Cookies

Đối tượng Cookies trong ASP.NET

Có lẽ bạn cũng đã từng đăng ký là một thành viên của một trang web hay một forum nào đó, và chắc cũng không ít lần ngạc nhiên khi bạn vừa yêu cầu đến một trang web hay forum mà bạn đã đăng ký trước đó, trang web nhận ngay ra, bạn chính là thành viên của họ và gởi ngay lời chào đến bạn, chẳng hạn: Chào Nguyễn Văn An.
    Những thông tin của bạn khi đăng nhập hay khi đăng ký được lưu ngay chính tại máy của bạn. Những thông tin này được Web Server lưu tại máy Client được gọi là Cookies.
Không giống như đối tượng Session, đối tượng Cookies cũng được dùng để lưu trữ thông
tin của người dùng, tuy nhiên, thông tin này được lưu ngay tại máy gởi yêu cầu đến Web
Server. Có thể xem một Cookie như một tập tin (với kích thước khá nhỏ) được Web Server lưu tại máy của người dùng. Mỗi lần có yêu cầu đến Web Server, những thông tin của Cookies cũng sẽ được gởi theo về Server.

Cú pháp thêm cookie

Response.Cookies.Add(<HttpCookie>)


Ví dụ:

HttpCookie ck = new HttpCookie("TenDangNhap");
ck.Value = txtTenDangNhap.Text;
ck.Expires = DateTime.Now.AddDays(15);
Response.Cookies.Add(ck);

Trong thí dụ trên, chúng ta đã tạo ra Cookies có tên là TenDangNhap lưu trữ tên đăng nhập của người dùng. Thông tin này sẽ được lưu trữ trên Cookies 15 ngày kể từ ngày hiện hành trên Web Server.

Cú pháp lấy giá trị từ Cookies

HttpCookie ck = Request.Cookies["TenDangNhap"]; 
string s = ck.Value;

Trong trường hợp Cookies chưa được lưu hoặc đã hết thời hạn duy trì tại Client, giá trị nhận được là null.

Ví dụ: Tạo 2 trang web: Trang Login.aspx và trang ReadCookie.aspx

Code trang Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1 {
            width: 61px;
        }
        .auto-style2 {
            width: 30px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <table style="width: 39%; border:groove">
            <tr>
                <td colspan="2" align="center"><b>Đăng nhập</b><hr /></td>
            </tr>
            <tr>
                <td class="auto-style2">Username:</td>
                <td class="auto-style1">
                    <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style2">Password:</td>
                <td class="auto-style1">
                    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style2">&nbsp;</td>
                <td class="auto-style1">
                    <asp:Button ID="btnLogin" runat="server" Text="Đăng nhập" Width="88px" OnClick="btnLogin_Click" />
                </td>
            </tr>
        </table>
    
    </div>
    </form>
</body>
</html>

Code behind trang Login.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        string username = txtUsername.Text;
        string password = txtPassword.Text;
        if (username == "admin" & password == "admin")
        {
            HttpCookie ck = new HttpCookie("username");
            ck.Value = username;
            ck.Expires = DateTime.Now.AddDays(15);//Hết hạn là 15 ngày
            Response.Cookies.Add(ck);
            Response.Redirect("ReadCookie.aspx");
        }
        else
            Response.Write("Username hoặc mật khẩu không đúng");
    }
}

Code trang ReadCookie.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReadCookie.aspx.cs" Inherits="ReadCookie" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="lblReadCookie" runat="server"></asp:Label>
    
    </div>
    </form>
</body>
</html>

Code behind trang ReadCookie.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ReadCookie : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie ck = Request.Cookies["username"];
        lblReadCookie.Text = "Xin chào, " + ck.Value;
    }
}

Thực thi code trang Login.aspx cho kết quả:

Nhập username=adminpassword=admin, click vào nút đăng nhập chuyển qua trang ReadCookie.aspx cho kết quả: