HTTP 是一种无状态的协议。
默认情况下,HTTP 请求之间是独立的。
下面讨论如何让HTTP 请求之间共享数据。
状态管理
状态有几种保存方式:
- Cookies,HTTP cookies,
- Session state,HTTP cookies 和服务端代码
- TempData, HTTP cookies 或者 session state
- Query strings,HTTP 请求的字符串
- 隐藏字段 ,HTTP 表单字段
- HttpContext.Items,服务端代码
- Cache,,服务端代码
SignalR
SignalR 不应该保存 Session state或者其他HTTP 的上下文状态,最多把 connection 相关的数据保存在 Hub 中。
Cookies
Cookies 保存跨请求的数据,因为每次请求都被带上了。
Cookies 应该保存最少的数据,不超过4096个字节。
Cookies 可以被客户端修改。
Cookies 应该只用来识别用户但不能用于验证用户。
Session state
ASP.NET Core 通过客户端提供的Cookie ID 保存一个Session ID。
Session cookie 不能跨浏览器。
Session cookie 在浏览器关闭后删除。
Cookie 过期后会生成新的Session ID。
在 View 中获取 Session:
@page
@using Microsoft.AspNetCore.Http
@model IndexModel
Name: @HttpContext.Session.GetString(IndexModel.SessionKeyName)
在 Action 中 set 和 get Session:
public class IndexModel : PageModel
{
public const string SessionKeyName = "_Name";
public const string SessionKeyAge = "_Age";
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
if (string.IsNullOrEmpty(HttpContext.Session.GetString(SessionKeyName)))
{
HttpContext.Session.SetString(SessionKeyName, "The Doctor");
HttpContext.Session.SetInt32(SessionKeyAge, 73);
}
var name = HttpContext.Session.GetString(SessionKeyName);
var age = HttpContext.Session.GetInt32(SessionKeyAge).ToString();
_logger.LogInformation("Session Name: {Name}", name);
_logger.LogInformation("Session Age: {Age}", age);
}
}
TempData
TempData 可以用于重定向。
TempData 使用 Cookie 和 Session 数据。