ASP.NET Core 应用程序状态
在ASP.NET Core中,由多种途径可以对应用程序状态进行管理,使用哪种途径,由检索状态的时机和方式决定。
应用程序状态指的是用于描述当前状况的任意数据。包括全局和用户特有的数据。
开发人员可以根据不同的因素来选择不同的方式存储状态数据:
数据需要存储多久
数据有多大
数据的格式是什么
数据是否可以序列化
数据有多敏感
数据能否保存在客户端
1.可选方式
1.HttpContext.Items
当数据仅用于一个请求中时,用Items集合存储时最好的方式。数据将在每个请求结束之后丢弃。它是组件和中间件在一个请求中的不同时间点金总互相通信的最佳手段。
HttpContext抽象提供了一个简单的IDictionary<object,object>类型的字典集合,就是Items。在每个请求中,这个集合从HttpRequest开始就可以使用,直到请求结束丢弃。要想存取集合,可以直接赋值和根据键查询。
app.Use(async (context,next) =>
{
context.Items["isExist"] = true;
await next.Invoke();
}); //在之后的管道查询值
app.Run(async (context) =>
{
await context.Response.WriteAsync("Is Exist:"+context.Items["isExist"]);
});
2.QueryString 和 Post
在查询字符串(QueryString )中添加值,或利用Post发送数据,可以将一个请求的状态数据提供给另一个请求。这不适合敏感数据,因为这需要将数据发送到客户端,然后再发送给服务器。这种方法也只适用于少量数据。用户提交的数据是无法预期的,带查询字符串的网址很容易泄露,所以要避免跨网站请求伪装攻击(CSRF)。
3.Cookies
与状态有关的小量数据可以存储在Cookies中。他们会随每次请求被发送到客户端。应该只使用一个标识符,真正的数据存储在服务端,服务端的数据与这个标识关联。
4.Session
会话存储依靠一个基于Cookie的标识符来访问与给定浏览器相关的会话数据。一个会话可以与多个Cookie关联。
5.Cache
缓存提供了一种方法,用自定义的键对应用程序数据进行存储和检索。它提供了一套基于时间和其他因素使缓存过期的规则。
6.其他
还可以使用EF和数据库等进行存储应用程序状态。
2.使用Session
首先要安装Microsoft.AspNetCore.Session安装包。然后在Startup类中配置。Session是基于IDistributedCache构建的,因此必须先配置好Session,否则会报错。
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.Cookie.Name = "Test.Session";
options.IdleTimeout = TimeSpan.FromSeconds();
});
ASP.NET 提供了IDistributedCache的多种实现,in-memory是其中之一。上面采用in-memory,需要先安装Microsoft.Extensions.Caching.Memory,然后添加上面代码。
最后在Configure中调用 app.UseSession(),需要在app.UseMvc使用之前调用。
(1)实现细节
Session利用一个cookie来跟踪和区分不同浏览器发出的请求。默认情况下,这个cookie被命名为“.ASP.Session”,并使用路径“/”。默认情况下,这个cookie不指定域,而且对于页面的客户端脚本是不可使用的,因为CookieHttpOnly默认为True。
其他的值可以通过SessionOptions配置:
services.AddSession(options =>
{
options.Cookie.Name = "Test.Session";
options.IdleTimeout = TimeSpan.FromSeconds();
});
IdleTimeout 在服务端决定过期时间,session的过期时间是独立于cookie的。
(2)ISession
安装和配置好session之后,就可以通过HttpContext的一个名为Session,类型为ISession的属性来引用会话。
public interface ISession
{
//
// 摘要:
// Indicate whether the current session has loaded.
bool IsAvailable { get; }
//
// 摘要:
// A unique identifier for the current session. This is not the same as the session
// cookie since the cookie lifetime may not be the same as the session entry lifetime
// in the data store.
string Id { get; }
//
// 摘要:
// Enumerates all the keys, if any.
IEnumerable<string> Keys { get; } //
// 摘要:
// Remove all entries from the current session, if any. The session cookie is not
// removed.
void Clear();
//
// 摘要:
// Store the session in the data store. This may throw if the data store is unavailable.
Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken));
//
// 摘要:
// Load the session from the data store. This may throw if the data store is unavailable.
Task LoadAsync(CancellationToken cancellationToken = default(CancellationToken));
//
// 摘要:
// Remove the given key from the session if present.
//
// 参数:
// key:
void Remove(string key);
//
// 摘要:
// Set the given key and value in the current session. This will throw if the session
// was not established prior to sending the response.
//
// 参数:
// key:
//
// value:
void Set(string key, byte[] value);
//
// 摘要:
// Retrieve the value of the given key, if present.
//
// 参数:
// key:
//
// value:
bool TryGetValue(string key, out byte[] value);
}
因为Session是建立在IDistributedCache之上的,所以总是需要序列化被存储的对象实例。因此,这个接口是使用byte[]而不是直接使用object。string 和 int32 的简单类型可以直接使用:
HttpContext.Session.SetInt32("key",);
HttpContext.Session.GetInt32("key");
存储对象需要先把对象序列化为一个byte[]字节流。需要使用MemoryStream和 BinaryFormatter
/// <summary>
/// 将一个object对象序列化,返回一个byte[]
/// </summary>
/// <param name="obj">能序列化的对象</param>
/// <returns></returns>
public static byte[] ObjectToBytes(object obj)
{
using (MemoryStream ms = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); return ms.GetBuffer();
}
}
/// <summary>
/// 将一个序列化后的byte[]数组还原
/// </summary>
/// <param name="Bytes"></param>
/// <returns></returns>
public static object BytesToObject(byte[] Bytes)
{
using (MemoryStream ms = new MemoryStream(Bytes))
{
IFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(ms);
}
}
ASP.NET Core 应用程序状态的更多相关文章
- ASP.NET Core 中文文档 第三章 原理(13)管理应用程序状态
原文:Managing Application State 作者:Steve Smith 翻译:姚阿勇(Dr.Yao) 校对:高嵩 在 ASP.NET Core 中,有多种途径可以对应用程序的状态进行 ...
- [转]ASP.NET Core基本原理(11)-管理应用程序状态
本文转自:http://zhuchenglin.me/fundamentals-11-app-state?utm_source=tuicool&utm_medium=referral ASP. ...
- ASP.NET Core 中文文档 第四章 MVC(4.5)测试控制器逻辑
原文: Testing Controller Logic 作者: Steve Smith 翻译: 姚阿勇(Dr.Yao) 校对: 高嵩(Jack) ASP.NET MVC 应用程序的控制器应当小巧并专 ...
- ASP.NET Core 运行原理剖析1:初始化WebApp模版并运行
ASP.NET Core 运行原理剖析1:初始化WebApp模版并运行 核心框架 ASP.NET Core APP 创建与运行 总结 之前两篇文章简析.NET Core 以及与 .NET Framew ...
- ASP.NET Core 防止跨站请求伪造(XSRF/CSRF)攻击
什么是反伪造攻击? 跨站点请求伪造(也称为XSRF或CSRF,发音为see-surf)是对Web托管应用程序的攻击,因为恶意网站可能会影响客户端浏览器和浏览器信任网站之间的交互.这种攻击是完全有可能的 ...
- ASP.NET Core 运行原理剖析
1. ASP.NET Core 运行原理剖析 1.1. 概述 1.2. 文件配置 1.2.1. Starup文件配置 Configure ConfigureServices 1.2.2. appset ...
- Centos7 编译安装 Nginx Mariadb Asp.net Core2 (实测 笔记 Centos 7.3 + Openssl 1.1.0h + Mariadb 10.3.7 + Nginx 1.14.0 + Asp.net. Core 2 )
环境: 系统硬件:vmware vsphere (CPU:2*4核,内存2G,双网卡) 系统版本:CentOS-7-x86_64-Minimal-1611.iso 安装步骤: 1.准备 1.0 查看硬 ...
- .NET CORE学习笔记系列(5)——ASP.NET CORE的运行原理解析
一.概述 在ASP.NET Core之前,ASP.NET Framework应用程序由IIS加载.Web应用程序的入口点由InetMgr.exe创建并调用托管,初始化过程中触发HttpApplicat ...
- ASP.NET Core依赖注入——依赖注入最佳实践
在这篇文章中,我们将深入研究.NET Core和ASP.NET Core MVC中的依赖注入,将介绍几乎所有可能的选项,依赖注入是ASP.Net Core的核心,我将分享在ASP.Net Core应用 ...
随机推荐
- Excel数据导入到Sql server
问题:数据库内直接操作导致 错误 0xc020901c: 数据流任务 1: 源 - yndata1$.输出[Excel 源输出] 上的 源 - yndata1$.输出[Excel 源输出].列[ind ...
- odoo10学习笔记四:onchange、唯一性约束
转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/11189273.html 一:onchange机制[onchange=前端js函数!可以实现前端实时更新以及修 ...
- [原创]python爬虫之BeautifulSoup,爬取网页上所有图片标题并存储到本地文件
from bs4 import BeautifulSoup import requests import re import os r = requests.get("https://re. ...
- springboot常见问题
什么是 Spring Boot? 为什么要用 Spring Boot? Spring Boot 的核心配置文件有哪几个?它们的区别是什么? Spring Boot 的配置文件有哪几种格式?它们有什么区 ...
- dl-google.com 的问题
印象里,如果用过公司vpn之后,再用android studio, 这个地址就能被解析下载了. 看来,应该只是域名被屏蔽,ip并没有. 所以,以后拿到ip之后,写进hosts里应该没事 https:/ ...
- odoo fields_view_get
odoo fields_view_get创建动态视图方法 odoo fields_view_get方法是一个比较有用比较灵活的广泛,如果使用得当,可以做到一些常规方法无法实现的功能,本文列举若干种用 ...
- 交换机端口与Mac地址绑定(基于Cisco模拟器)
实验设备: 二层交换机一台,主机三台 实验步骤: 1.进入相应的接口 (以端口1设置Mac地址绑定,PC0接1端口举例) Switch>enable Switch#config Configur ...
- Linux性能优化实战学习笔记:第三十一讲
一.上节回顾 上一节,我们一起回顾了常见的文件系统和磁盘 I/O 性能指标,梳理了核心的 I/O 性能观测工具,最后还总结了快速分析 I/O 性能问题的思路. 虽然 I/O 的性能指标很多,相应的性能 ...
- [LeetCode] 862. Shortest Subarray with Sum at Least K 和至少为K的最短子数组
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there ...
- k8s学习路线
1. 核心概念说明 http://dockone.io/article/932 https://www.centos.bz/2017/08/k8s-kubernetes-architecture-di ...