TOC

This article is currently in the process of being translated into Vietnamese (~64% done).

HttpContext:

Cookies

HTTP, giao thức truyền tải liên lạc giữa máy chủ và người dùng trên web, được biết tới là giao thức phi trạng thái. Nói cách khác, là nếu người dùng yêu cầu 2 trang với máy chủ, sẽ không có thông tin nào được chia sẻ tự động giữa 2 yêu cầu này. Thay vào đó, lập trình viên sẽ phải dựa vào cookies (hoặc session - sẽ được nhắc tới nhiều hơn sau) để chia sẻ thông tin giữa các yêu cầu. Điều này cực kì hữu dụng trong nhiều trường hợp, ví dụ là giúp người dùng vẫn trong trang thái đăng nhập giữ các yêu cầu.

Hầu hết các công nghệ server-side có sẵn hỗ trợ cho việc xử lí cookie và tất yếu là khung ASP.NET MVC cũng có. Thật ra việc sử dụng cookie khá là dễ, nhờ vào những ứng dụng có trong lớp HttpContext. Trong bài viết này, bạn sẽ học cách làm sao để tạo cookie và đọc nó sau đó, với mục tiêu là cho phép bạn chia sẻ thông tin của một người dùng nhất định giữa các yêu cầu của người đó.

Cookie là gì?

Cookie cơ bản chỉ là một tập tin văn bản text (.txt) thông thường, lưu trữ bởi người dùng (thường thông qua trình duyệt web), liên với một website nhất định. Người dùng sau đó sẽ cho phép website này đọc thông tin lưu trữ trong tập tin này khi có những yêu cầu sau đó, về cơ bản là cho phép máy chủ (hoặc là cả máy người dùng) lưu trữ thông tin lại để sử dụng về sau.

Thiết lập và đọc cookie

Để tạo cookie và sau đó đọc, thì đối với ASP.NET MVC là rất rất dễ dàng. Dưới đây là cách để có thể gửi cookie đến người dùng trong trạng thái đơn giản nhất:

HttpContext.Response.Cookies.Append("user_id", "1");

Chú ý về việc sử dụng Response property lên lớp HttpContext, tại đó, ta có thể truy cập vào Cookies property. Sử dụng phương thức Append(), ta có thể thêm Cookie vào đầu ra, bằng cách cung cấp tên và giá trị cho nó. Tên (user_id) sẽ được dùng sau để lấy lại giá trị (1).Và lấy giá trị này lại cũng dễ không kém:

var userId = HttpContext.Request.Cookies["user_id"];

Chú ý về việc sử dụng Request property thay vì Response khi đọc giá trị, nguyên nhân là việc tạo cookie bằng các thêm thông tin vào phản hồi trả về cho người dùng, trong khi đó, việc đọc là thông tin sẽ được trích xuất từ yêu cầu tạo ra bởi người dùng (một trình duyệt thông thường sẽ tự động gửi các cookie có liên quan đối với mỗi yêu cầu).

Qua đây, ta đã có thể viết và đọc thông tin của cookie, giờ ta sẽ kết hợp lại một ví dụ cực kì đơn giản, trong đó, ta thêm một mảnh thông tin dưới dạng cookie nếu nó chưa tồn tại sẵn, đây sẽ là phương pháp hiệu quả để biết rằng người sử dụng đã đến trang chưa hay không:

public class CookiesController : Controller
{
    public IActionResult Index()
    {
if(!HttpContext.Request.Cookies.ContainsKey("first_request"))
{
    HttpContext.Response.Cookies.Append("first_request", DateTime.Now.ToString());
    return Content("Welcome, new visitor!");
}
else
{
    DateTime firstRequest = DateTime.Parse(HttpContext.Request.Cookies["first_request"]);
    return Content("Welcome back, user! You first visited us on: " + firstRequest.ToString());
}
    }
}

Từ đây, Controller tạo thành phản hồi dựa trên người đã từng truy cập vào trang trước đó bao giờ chưa, bằng cách luôn kiểm tra sự hiện diện của cookie với tên "first_request", nếu cookie này không tồn tại, nó sẽ được thêm vào, với giá trị thiết lập tại ngày và thời gian lúc đó. Nếu cookie đó có tồn tại, có thể xem là người dùng này đã truy cập trang trước và ta còn có thể biết được lần đầu truy cập của người dùng là khi nào.

Đây là những yếu tố cơ bản của cookie và cách viết và đọc những cookie đó. Tuy nhiên, vẫn còn thêm một ít nữa để có sử dụng hết những lợi ít từ cookie

CookieOptions

Sử dụng làm thông số (không bắt buộc) thứ 3 cho phương thức Append() vừa sử dụng, ta có thể đưa thêm một trường hợp vào cho lớp CookieOptions. Lớp này cho phép điều chỉnh một số khía cạnh quan trọng của cookie, ví dụ như cookie đó nên tồn tại bao lâu và những yếu tố như domain và đường dẫn. Cho phép tôi nói về các yếu tố quan trọng nhậm, thế nhưng đầu tiên, cần phải thêm vào namespace Microsoft.AspNetCore.Http, nơi chứa lớp CookieOptions:

using Microsoft.AspNetCore.Http;

Từ đây, một trường hợp cho lớp CookieOption có thể được tạo thành, trường hợp này sẽ sử dụng hiệu chỉnh mặc định, và sau đó đưa vào phương thức Append():

CookieOptions cookieOptions = new CookieOptions();            
HttpContext.Response.Cookies.Append("first_request", DateTime.Now.ToString(), cookieOptions);

Before passing it though (so, between the two lines of code), you likely want to change some of the options. Here are the most relevant ones:

CookieOptions.Expires

By default, your cookie will be a so-called session cookie, meaning that it will only live as long as the browser remains open - once the browser is closed, the cookie is deleted by the browser. However, you are free to change this behavior using the Expires property. This property is a DateTimeOffset instance, which makes it easy to configure an expiry time, like this:

cookieOptions.Expires = new DateTimeOffset(DateTime.Now.AddDays(7));

This will make the cookie expire in 7 days. You can of course adjust this using the methods like AddDays(), AddHours() and so on.

CookieOptions.Domain

By default, the cookie will be set for the domain which made the request. So, if your page is accessed by the domain mywebsite.com, the cookie will be set for mywebsite.com. If your page is accessed using a subdomain, this subdomain will be used, and this is important, because a subdomain could be "www". So, if your page is accessed by www.mywebsite.com, the cookie will, by default, only be accessible from www.mywebsite.com and NOT mywebsite.com. Therefore, it can be a good idea to set the Domain property to the base-domain of your website, prefixed with a dot, like this:

cookieOptions.Domain = ".mywebsite.com";

Now your cookie will be accessible from mywebsite.com as well as all possible subdomains. On the other hand, if you don't have full control over the domain, you may want to limit the domain of the cookie to the specific (sub)domain you control.

CookieOptions.Path

By default, the Path of the cookie will be set to "/", which basically means that the cookie will be valid for all pages of the website. However, under certain conditions, you may need a cookie that's valid only for a specific page or folder. This is easily accomplished with the Path property:

cookieOptions.Path = "/users/";

With that in place, the cookie will now only be visible and readable to pages in the "users" folder, as well as sub-folders to it.

More properties of CookieOptions

There are several other interesting properties to be found on CookieOptions, like IsEssential, HttpOnly and Secure. If you want to know more about them, I suggest that you have a look at the documentation for CookieOptions.

Summary

Thanks to cookies, you can save information about the visitor and retrieve it again on subsequent requests. This is a very important technique, used in a wide range of situations, like keeping the user logged in, tracking their use of your website and much more.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!