ASP.NET Core 中的状态管理

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 数据。

Query strings

隐藏字段

HttpContext.Items

Cache

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值