24/05/2018, 22:04

Trạng thái

Cookie làm việc như thế nào? Khi trình duyệt web tạo một Cookie, một nội dung sẽ được lưu vào header của trang web với nội dung giống như sau: Set-Cookie: Message=Hello Phần tiêu đề Set-Cookie này gây ra ...

Cookie làm việc như thế nào?

Khi trình duyệt web tạo một Cookie, một nội dung sẽ được lưu vào header của trang web với nội dung giống như sau:

Set-Cookie: Message=Hello
    

Phần tiêu đề Set-Cookie này gây ra cho trình duyệt web tạo một Cookie có tên là

Message và giá trị của nó là Hello.

Sau khi một Cookie được tạo trên trình duyệt, Mỗi khi trình duyệt yêu cầu một trang web trong ứng dụng, trình duyệt sẽ gửi một header có dạng giống như sau:

Cookie: Message=Hello

Bạn có thể tạo hai kiểu của Cookie, Session Cookies và Persistent Cookies. Session cookies chỉ tồn tại trong bộ nhớ khi trình duyệt web bị đóng lại thì nó cũng bị xóa đi.

Còn Persistent Cookies có thể tồn tại hàng tháng hoặc hàng năm. Khi bạn tạo một

Còn Persistent Cookies có thể tồn tại hàng tháng hoặc hàng năm. Khi bạn tạo một Persistent Cookies, nó sẽ được lưu trữ trên web browse trên máy tính của bạn. với IE ví dụ nó sẽ được lưu trữ trong một file Text theo thư mục

Còn với FireFox nó lưu trữ trong thư mục theo đường dẫn sau:

Documents and Settings[user]Application DataMozillaFirefoxProfiles[random folder name]Cookies.txt

bởi vì sự lưu trữ cookies trên các trình duyệt khác nhau để ở các thư mục khác nhau lên khi bạn tạo Cookies trên IE thì nó sẽ không tồn tại trên FireFox và ngược lại.

B o m ật với C o okie

Bảo mật với Cookie

Tạo Cookies

Bạn có thể tạo cookies với câu lệnh Response.Cookies, tất cả các Cookies sẽ được gửi từ Web Server đến Web Browser.

Tạo ra một Cookies Message với giá trị được lấy từ hộp TextBox trên Form
 <%@ Page Language="C#" AutoEventWireup="true"	CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<script runat="server">
protected void Add_Click(object sender, EventArgs e)
{
Response.Cookies["Message"].Value = txtCookies.Text;
}
</script>
<!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>Create Cookies</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Cookie Value"></asp:Label>
<asp:TextBox ID="txtCookies" runat="server"></asp:TextBox>
<asp:Button ID="Add" runat="server" OnClick"Add_Click" Text="Button"
/>
</div>
</form>
</body>
</html>
Trang setCookies.aspx

Trong ví dụ một là chúng ta tạo ra một Session Cookies, còn nếu bạn muốn tạo một Persistent Cookies bạn cần chỉ định thời hạn kết thúc cho Cookies .

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="setPersistentCookies.aspx.cs" Inherits="setPersistentCookies" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
int counter=0;
if (Request.Cookies["counter"] != null)
counter = Int32.Parse(Request.Cookies["counter"].Value);
counter++;
Response.Cookies["counter"].Value = counter.ToString(); Response.Cookies["counter"].Expires = DateTime.Now.AddYears(2); this.Label1.Text = Response.Cookies["counter"].Value;
}
</script>
<!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>Set Persitent Cookies</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
 Trang setPersistentCookies.aspx

Trong ví dụ trên khi chạy chương trình mỗi lần bạn Refresh lại trang thì giá trị của Label1 sẽ tăng lên một. Và với câu lệnh

 Response.Cookies["counter"].Expires=Datetime.Now.AddYears(2)
, có nghĩa là thời gian tồn tại của Cookie này sẽ là 2 năm.

Đọc dữ liệu từ Cookies

Bạn sử dụng lện Request.Cookies để lấy dữ liệu từ Cookies, bạn xem lại ví dụ 2 trang setPersistentCookies.aspx.

Khi bạn có một tập hợp các Cookies bạn có thể lấy tât cả giá trị của các Cookies trên website của mình, ví dụ sau đây sẽ hướng dẫn bạn làm việc đó.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GetAllCookies.aspx.cs"
Inherits="GetAllCookies" %>
<script runat="server">
void Page_Load()
{
ArrayList colCookies = new ArrayList();
for (int i = 0; i < Request.Cookies.Count; i++)
colCookies.Add(Request.Cookies[i]); grdCookies.DataSource = colCookies; grdCookies.DataBind();
}
</script>
<!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>Get All Cookies</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grdCookies" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
trang GetallCookies

Thiết lập thuộc tính cho Cookies

Cookies được đưa ra với lớp HttpCookie, khi bạn tạo hoặc lấy giá trị từ một Cookie có thể bạn sẽ sử dụng một vài thuộc tính của lớp này:

  • Domain: cho phép bạn chỉ định Domain kết hợp với Cookie. Giá trị mặc định là Domain hiện tại.
  • Expires: Cho phép tạo Persistent Cookies với thời hạn được chỉ định
  • HasKeys: Cho phép bạn định rõ Cookies có nhiều giá trị hay không.
  • HttpOnly: Cho phép đưa ra một Cookies từ JavaScript.
  • Name: chỉ định tên cho Cookies.
    • Path: Cho phép chỉ định đường dẫn kết hợp với Cookies. Giá trị mặc định là /.
  • Secure:Cho phép một Cookie được chuyển tác ngang tới kết nối Sercure Sockets Layer (SSL).
  • Value:Cho phép lấy hoặc thiết lập giá trị cho Cooki
  • Values: Cho phép bạn lấy hoặc thiết lập giá trị riêng khi làm việc với Cookies có nhiều giá trị.

Xóa Cookies

Để xóa một Cookie bạn thiết lập ngày hết hạn cho Cookies là -1

Ví dụ như câu lệnh dưới đây:

Response.Cookies[“Message”].Expires = DateTime.Now.AddDays(-1);

Trên ví dụ trên chúng ta sẽ xóa Cookie vơi tên là Message.

Làm việc với Cookies nhiều giá trị:

Trong trình duyệt không lên lưu trưc hơn 20 Cookies từ một Domain, thay vào đó bạn có thể làm việc với một Cookie nhiều giá trị.

Một Cookies nhiều giá trị là một Cookies đơn chứa đựng nhiều khóa con, bạn có thể tạo nhiều khóa con như bạn muốn.

Như ví dụ dưới đây bạn tạo ra một Cookies Person nhiều giá trị, Cookie Person lưu trữ các giá trị Họ tên, Ngày sinh và màu sắc yêu thích.

Trang SetCookieValues.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="SetCookieValues.aspx.cs" Inherits="SetCookieValues" %>
<script runat="server">
protected void btnsubmit_Click(object sender, EventArgs e)
{
Response.Cookies["Person"]["Hoten"] = txtHoten.Text; Response.Cookies["Person"]["Ngaysinh"] = txtNgaysinh.Text; Response.Cookies["Person"]["Color"] = txtColor.Text; Response.Cookies["Person"].Expires = DateTime.MaxValue;
}
</script>
<!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>Set Cookie MutilValues</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Họ  tên</td>
<td><asp:TextBox ID="txtHoten" runat="server" /></td>
</tr>
<tr>
<td>Ngày sinh</td>
<td><asp:TextBox ID="txtNgaysinh" runat="server" /></td>
</tr>
<tr>
<td>Màu yêu thích</td>
<td><asp:TextBox ID="txtColor" runat="server" /></td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClick="btnsubmit_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Việc lấy giá trị của Cookie nhiều giá trị tương tự như các phần trên, học viên về nhà hoàn thiện nốt.

Bạn có thể chưa thực sự dùng Cookies để lưu trữ Shoping Cart. Một Cookie vừa quá nhỏ và quá đơn giản. Để làm việc ngoài giới hạn của Cookie ASP.NET Framework hỗ trợ một chức năng mới được gọi là Session State

Giống với Cookie Session lưu trữ dữ liệu trong phạm vi riêng với từng người sử dụng. Nhưng không giống với Cookie Session không giới hạn dung lượng, nếu bạn cần bạn có thể lưu trữ hàng Gigabyte dữ liệu, hơn thế nữa Session có thể đưa ra điều đối tượng phức tạp hơn là chuỗi Text. Bạn có thể lưu trữ một vài đối tượng trong Session. Ví dụ bạn có thể lưu trữ một Dataset hay một Shoping cart trong Session.

Thêm dữ liệu vào Session

Bạn thêm dữ liệu vào trạng thái Session bằng việc sử dụng đối tượng Session, Ví dụ sau đây sẽ thêm một dữ liệu vào Session có tên là Message và giá trị của nó là “Hello World”

<%@ Page Language="C#" AutoEventWireup="true"	CodeFile="Sessionset.aspx.cs"
Inherits="_Default" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Session["Message"] = "Hello World";
}
</script>
<!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>Session set</title>
</head>
<body>
<form id="form1" runat="server">
 <div>
<h1>Session state item added!</h1>
</div>
</form>
</body>
</html>
Trang Sessionset.aspx

Lấy dữ liệu từ một Session

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Sessionget.aspx.cs"
Inherits="Sessionget" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
lblsession.Text = Session["Message"].ToString();
}
</script>
<!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>Session get</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblsession" runat="server" />
</div>
</form>
</body>
</html>
Trang Sessionset.aspx

Bạn lưu ý rằng cũng như Cookie khi một Session được tạo ra, một trạng thái session có tên ASP.NET_SessionID được tự động thêm vào trình duyệt của bạn và Session này được lưu trữ trên web server và không lưu trữ trên webClient. Và khi bạn tắt trình duyệt đi thì Session này của bạn vẫn tồn tại trong khoảng thời gian quy định, mà ASP.NET Framework quy định thời gian mặc định của Session là 20 phút. bạn có thể thiểt lập thời gian nhiều hơn.

Lưu trữ cơ sở dữ liệu trong Session

Bạn có thể tạo Session state để tạo một vùng nhớ cho người sử dụng. ví dụ bạn có thể tải dữ liệu cho một người sử dụng và cho phép người sử dụng đó sắp xếp hay lọc dữ liệu.

Sử dụng đối tượng Session

Chương trình ứng dụng chính giao tiếp và làm việc với Session State là lớp HttpSessionState. Đối tượng này được thể hiện bới các thuộc tính Page.Session, Context.Session, UserControl.Session, Webservice.Session và Application.Session. có nghĩa là bạn có thể làm việc với Session bất kỳ đâu trong ứng dụng web.

Lớp HttpSessionState hỗ trợ các thuộc tính sau:

  • CookieMode: có cho phép Cookie Session hay không?
  • Count: cho phép lấy số dữ liệu trong Session State
  • IsCookieless: Cho phép chỉ rõ có cho phép Cookieless hay không?
  • IsNewSession—Enables you to determine whether a new user session was created
  • with the current request.
  • IsReadOnly—Enables you to determine whether the Session state is read-only.
  • Keys—Enables you to retrieve a list of item names stored in Session state.
  • Mode—Enables you to determine the current Session state store provider. Possible
  • values are Custom, InProc, Off, SqlServer, and StateServer.
  • SessionID—Enables you to retrieve the unique session identifier.
  • Timeout—Enables you to specify the amount of time in minutes before the web
  • server assumes that the user has left and discards the session. The maximum value is 525,600 (1 year).

Đối tượng HttpSessionState hỗ trợ các phương thức sau:

  • Abandon: Cho phép kết thúc Session của một người sử dụng.
  • Clear: Cho phép xoá toàn bộ dữ liệu trong Session State.
  • Remove: cho phép bạn xoá từng phần tử trong Session State

Điều khiển sự kiện Session

Có hai sự kiện có liên quan với Session State mà bạn có thể điều khiển nó trong file Global.asax là sự kiện Session_Start và Session_End.

Session_Start xảy ra khi một Sesion mới của người sử dụng được tạo ra. Bạn có thể sử dụng sự kiện này để load thông tin của người sử dụng ra từ cơ sở dữ liệu. Ví dụ bạn có thể tải dữ liệu về Shoping cart của người sử dụng trong sự kiện này .

Session_End xảy ra khi kết thúc Session, một Session kết thúc khi thời hạn của Session hết hoặc bởi viêcj chỉ định của phương thức Session.Abadon. Ví dụ Khi bạn muốn tự động ghi giỏ hàng của người sử dụng vào bảng dữ liệu trong cơ sở dữ liệu khi Session_End xảy ra.

Điều khiển khi Session quá hạn

Mặc định ASP.NET Framework quy định thời gian quá hạn của Session là 20 phút, trong nhiều trường hợp bạn thấy như vậy là quá ít, và bạn nghĩ rằng bạn cần thay đổi thời gian này.

Ví dụ trong trường hợp bạn tạo một trang quản trị của website, khi cập nhật dữ liệu bạn có một bài viết dài, và thời hạn 20 phút không thể đủ thời gian cho bạn cập nhật tin đó, và để hoàn thành bài đó có thể bạn phải mất 1 giờ.

Sự bất lợi là nếu tăng thời gian quá hạn của Session lên thì bộ nhớ của ứng dụng càng phải sử dụng nhiều, vì vậy khi bạn tăng thời hạn của Session thì bộ nhớ của Server sẽ phải dùng càng nhiều.

Tuy nhiên nếu cần bạn vẫn có thể tăng thời hạn của Session bằng cách bạn có thể chỉ định thời gian quá hạn của Session trong file web.config

<configuration>
<system.web>
<sessionState timeout="" />
</system.web>
</configuration>

Sử dụng Cookieless Session State

Mặc định Session State dựa trên Cookie. ASPNET Framework sử dụng ASP.NET_SessionId Cookie để định danh người sử dụng trên website mà dữ liệu có thể được kết hợp với người sử dụng, nếu người sử dụng vô hiệu hóa Cookie trên trình duyệt thì Session State sẽ không làm việc.

Để Session có thể làm việc khi trình duyệt vô hiệu hóa Cookie bạn cần thêm vào Cookieless Session. Khi Cookieless Session được cho phép, thì Session ID của người sử dụng sẽ được thêm vào trang URL.

Đây là một ví dụ của trang URL nhìn giống với khi Cookieless Session được cho phép.http://localhost:4945/Original/(S(5pnh11553sszre45oevthxnn))SomePage.aspx.

Bạn cho phép Cookieless Session bằng việc chỉnh sửa các thành phần SessionState trong file web.config. Thành phần SessionState bao gồm các một đặc tính cookieless mà nó chấp nhận các giá trị sau:

  • AutoDetect: SessionID được lưu trữ trong một cookie khi trình duyệt có cho phép Cookie. Ngược lại thì nó lưu trữ vào địa chỉ URL.
  • UseCookies: Session ID luôn luôn lưu trữ trong cookie
  • UseDeviceProfile: Session ID lưu trữ trong cookie khi trình duyệt hỗ trợ Cookie, trường hợp ngược lại nó lưu trữ trong địa chỉ URL.
  • UseUri: Session ID luôn luôn được thêm vào URL.

Trong ví dụ sau đây chúng ta thiết lập cookieless là AutoDetect như vậy ASP.NET Framework sẽ kiểm tra sự tồn tại cảu HTTP Cookie header, nếu Cookie header được tìm thấy thì Framework sẽ lưu trữ Session trong một cookie và ngược lại thì nó sẽ thêm vào URL.

<configuration>
<system.web>
<sessionState cookieless="AutoDetect"
regenerateExpiredSessionId="true"/>
</system.web>
</configuration>

ASP.NET Framework cung cấp cho bạn một thay thế cho Session hay cookie để lưu trữ thông tin của người sử dụng đó là đối tượng Profile

Bạn tạo một Profile bằng cách định nghĩa một danh sách các thuộc tính Profile trong ứng dụng ờ file web.config trong thư mục root. ASP.NET Framework tự động biên dịch một lớp chứa đựng các thuộc tính này.

Ví dụ sau đây sẽ đưa ra một Profile với ba thuộc tính: firstName, lastName và NumberOfVisits:

<?xml version=".0"?>
<configuration>
<system.web>
<profile>
<properties>
<add name="firstName" />
<add name="lastName"/>
<add name="NumberOfVisits" type="Int32" defaultValue="0"/>
</properties>
</profile>
</system.web>
</configuration>
Trang web.config

Khi làm việc với Profile bạn chú ý một số thuộc tính sau:

  • Name: chỉ định tên của thuộc tính.
  • Type: cho phép chỉ định kiểu dữ liệu của thuộc tính
  • Defaultvalue: cho phép chỉ định giá trị mặc định của thuộc tính
  • ReadOnly: cho phép tạo thuộc tính chỉ đọc
  • serializeAs: Enables you to specify how a property is persisted into a static repre-
  • sentation. Possible values are Binary, ProviderSpecific, String, and Xml.
  • allowAnonnyMous: cho phép người sử dụng nặc danh đọc và thiết lập thuộc tính
  • Provider: Cho phép bạn kết hợp thuộc tính với một Profile Provider riêng biêt.
  • customeProviderData:Enables you to pass custom data to a Profile provider.

Sau khi định nghĩa một Profile trong web.config, bạn có thể sử dụng đối tượng Provider để chỉnh sửa các thuộc tính Profile. Như ví dụ sau đây bạn sẽ chỉnh sửa hai thuộc tính firstName và lastName trên Form, hơn thế nữa chúng ta sẽ thấy mỗi lần trang web được load lại thì giá trị của NumberOfVisit sẽ tăng lên một.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="showProfile.aspx.cs"
Inherits="showProfile" %>
<script runat="server">
void Page_PreRender()
{
firstName.Text = Profile.firstName;
lastName.Text = Profile.lastName;
Profile.NumberOfVisits++;
numbervisit.Text = Profile.NumberOfVisits.ToString();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
Profile.firstName = txtFirstName.Text; Profile.lastName = txtLastName.Text;
}
</script>
<!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>show Profile</title>
</head>
<body>
<form id="form1" runat="server">
<div>
FirstName: <asp:Label ID="firstName" runat="server" /><br /> LastName: <asp:Label ID="lastName" runat="server" /><br />
Number of Visit: <asp:Label ID="numbervisit" runat="server" /><hr />
<asp:Label ID="lblfistname" runat="server" Text="FirstName:" />
<asp:TextBox ID="txtFirstName" runat="server" /><br />
<asp:Label ID="lbllastName" runat="server" Text="LastName:" />
<asp:TextBox ID="txtLastName" runat="server" /><br />
<asp:Button ID="btnUpdate" Text="Update" runat="server" OnClick="btnUpdate_Click" />
</div>
</form>
</body>
</html>
Trang showProfile.aspx

Và kết xuất của chương trình như sau:

Chú ý rằng thuộc tính của Profile được trình bày với kiểu dữ liệu đã quy định trong thuộc tính type mà ta định nghĩa trong Profile.

Một thuộc tính quan trọng của Profile nó là nó có khả năng giữ lại giá trị của thuộc tính khi người sử dụng rời khỏi trang web, ví dụ nếu bạn gán thuộc tính Profile cho một người sử dụng, người sử dụng đó không quay lại website trong 500 năm thì giá trị đó vẫn được giữ lại cho người sử dụng.

Đối tượng Profile sử dụng models Provider. mặc định Profile Provider là SqlProfileProvider, Mặc định Provider lưu trữ dữ liệu Profile trong cơ sở dữ liệu MS SQL Server 2005 Express được đặt tên là ASPNETDB.mdf, được định vị trong thư mục App_Data. Nếu cơ sở dữ liệu không tồn tại thì nó sẽ được tạo tự động khi chạy chương trình có sử dụng Profile.

MẶc định bạn không thể lưu trữ thông tin Profile cho một người sử dụng nặc danh. ASP.NET Framework tính đồng nhất authenticate của bạn kết hợp với thông tin Profile, bạn có thể sử dụng đối tượng Profile với các kiểu chuẩn mà authentication hỗ trợ bởi ASP.NET Framework, bao gồm cả hai kiểm chứng Forms và Windows

Creating Profile Groups

Nếu bạn cần định nghĩa nhiều thuộc tính của Profile, bạn có thể tạo các thuộc tính bằng quản lý bởi việc tổ chức các thuộc tính trong Groups. Ví dụ trong file web.config sau định nghĩa hai nhóm thuộc tính Preferences và ContactInfo.

<?xml version=".0"?>
<configuration>
<system.web>
<profile>
<properties>
<group name="Preferences">
<add name="BackColor" defaultValue="lightblue"/>
<add name="font" defaultValue="Arial"/>
</group>
<group name="ContactInfo">
<add name="Email" defaultValue="hung.le.uh@itechpro.com.vn"/>
<add name="phone" defaultValue="0936302728"/>
</group>
</properties>
</profile>
</system.web>
</configuration>
Trang web.config

Ví dụ sau đây sẽ hướng dẫn bạn cách tạo

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="showProfilegoups.aspx.cs" Inherits="showProfilegoups" %>
<%@ Import Namespace="System.Drawing" %>
<script runat="server">
protected void Page_Load()
{
lblEmail.Text = Profile.ContactInfo.Email; lblPhone.Text = Profile.ContactInfo.phone; Style pagestyle = new Style();
pagestyle.BackColor =
ColorTranslator.FromHtml(Profile.Preferences.BackColor);
pagestyle.Font.Name = Profile.Preferences.font;
Header.StyleSheet.CreateStyleRule(pagestyle, null,"html");
}
</script>
<!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>show profile group</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Email: <asp:Label ID="lblEmail" runat="server" /><br /> Phone: <asp:Label ID="lblPhone" runat="server" />
</div>
</form>
</body>
</html>

Hỗ trợ người sử dụng nặc danh

Mặc định người sử dụng nặc danh không thể chỉnh sửa các thuộc tính của Profile, vấn đề là ASPNET Framework không có phương thức kết hợp dữ liệu Profile với người sử dụng riêng biêt trừ khi người sử dụng được kiểm chứng.

Nếu bạn muốn cho phép người sử dụng nặc danh chỉnh sửa các thuộc tính Profile, bạn có phải cho phép đặc tính của ASP.NET Framework được gọi là định danh nặc danh. Khi định danh nặc danh được cho phép, khi định danh duy nhất được gán đến người sử dụng nặc danh và được lưu trữ trong trình duyệt cookie ổn định.

Hơn thế nữa, bạn phải đánh dấu tất cả các thuộc tính Profile mà bạn muốn cho phép người sử dụng nặc danh với các đặc tính cho phép nặc danh. Ví dụ trang web.config sau cho phép định danh nặc danh và định nghĩa một thuộc tính Profile mà có thể chỉnh sửa được bởi người sử dụng nặc danh.

<?xml version=".0"?>
<configuration>
<system.web>
<authentication mode="Windows" />
<anonymousIdentification enabled="true"/>
<profile>
<properties>
<add name="NumberOfVisits" type="Int32" defaultValue="0"
allowAnonymous="true"/>
</properties>
</profile>
</system.web>
</configuration>

Trong ví dụ sau sẽ hướng dẫn cách bạn sửa thuộc tính định danh khi định danh nặc danh được cho phép.

Trang ShowAnonymousIdentification.aspx;
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="ShowAnonymousIdentification.aspx.cs"
Inherits="ShowAnonymousIdentification" %>
<script runat="server">
void Page_PreRender()
{
lblName.Text = Profile.UserName;
lblanonymous.Text = Profile.IsAnonymous.ToString(); Profile.NumberOfVisits++;
lblnumbetofanonymous.Text = Profile.NumberOfVisits.ToString();
}
protected void btnLogin_Click(object sender, EventArgs e)
{
FormsAuthentication.SetAuthCookie("Bob", false);
Response.Redirect(Request.Path);
}
protected void btnLogout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut(); Response.Redirect(Request.Path);
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>Show Anonymous Identification</title>
</head>
<body>
<form id="form1" runat="server">
<div>
UseName: <asp:Label ID="lblName" runat="server" /><br />
Is Anonymous: <asp:Label ID="lblanonymous" runat="server" />
Number of Visits: <asp:Label ID="lblnumbetofanonymous" runat="server"
/><br /><hr />
<asp:Button ID="btnReload" Text="Reload" runat="server" />
<asp:Button ID="btnLogin" Text="Login" OnClick="btnLogin_Click"
runat="server" />
<asp:Button ID="btnLogout" Text="Logout" OnClick="btnLogout_Click"
runat="server" />
</div>
</form>
</body>
</html>
0