Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách bật Session trong C# ASP.NET Core

Session là tính năng trong ASP.NET Core cho phép lưu trữ dữ liệu người dùng.

Session lưu trữ dữ liệu trong dictionary trên Server và SessionId được dùng làm key. SessionId được lưu trên client ở cookie. Cookie SessionId được gửi kèm với mọi request.

Cookie SessionId là trên mỗi browser và không thể chia sẻ giữa các browser.

Không có timeout được chỉ định cho cookie SessionId và chúng bị xóa khi session browser kết thúc.

Ở phía Server, session được giữ lại trong thời gian giới hạn. Timeout session mặc định ở Server là 20 phút nhưng có thể cấu hình.

Package Microsoft.AspNetCore.Session cung cấp middleware để quản lý session trong ASP.NET Core. Để sử dụng session trong ứng dụng, chúng ta cần thêm package này như dependency trong file project.json (hoặc qua NuGet trong .csproj).

Bước tiếp theo là cấu hình session trong lớp Startup.

Chúng ta cần gọi phương thức "AddSession" trong phương thức ConfigureServices của lớp startup.

Phương thức "AddSession" có một overload method, chấp nhận các tùy chọn session như Idle Timeout, Cookie Name và Cookie Domain, v.v.

Nếu không truyền tùy chọn session, hệ thống sẽ lấy các tùy chọn mặc định.

Ví dụ cấu hình

public class Startup { 
    public void Configure(IApplicationBuilder app) { 
        app.UseSession(); 
        app.UseMvc(); 
        app.Run(context => { 
            return context.Response.WriteAsync("Hello World!"); 
        }); 
    } 
    
    public void ConfigureServices(IServiceCollection services) { 
        services.AddMvc(); 
        services.AddSession(options => { 
            options.IdleTimeout = TimeSpan.FromMinutes(60); 
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        }); 
    } 
}

Cách truy cập Session

public class HomeController : Controller { 
    [Route("home/index")] 
    public IActionResult Index() { 
        HttpContext.Session.SetString("product", "laptop"); 
        return View(); 
    } 
    
    [Route("home/GetSessionData")] 
    public IActionResult GetSessionData() { 
        ViewBag.data = HttpContext.Session.GetString("product"); 
        return View(); 
    } 
}

Các phương thức mở rộng Session phổ biến

  • SetString(key, value) - Lưu chuỗi
  • GetString(key) - Lấy chuỗi
  • SetInt32(key, value) - Lưu số nguyên
  • GetInt32(key) - Lấy số nguyên
  • Set(key, byte[]) - Lưu byte array
  • Get(key) - Lấy byte array
  • Remove(key) - Xóa key
  • Clear() - Xóa toàn bộ session

Cấu hình Session nâng cao

services.AddSession(options => {
    options.IdleTimeout = TimeSpan.FromMinutes(30);    // Timeout 30 phút
    options.Cookie.Name = ".MyApp.Session";            // Tên cookie tùy chỉnh
    options.Cookie.HttpOnly = true;                    // Chỉ truy cập qua HTTP
    options.Cookie.IsEssential = true;                 // Bắt buộc cho GDPR
    options.Cookie.SameSite = SameSiteMode.Lax;        // CSRF protection
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // Chỉ HTTPS
});