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应用 ...
随机推荐
- Spring获取springmvc的controller bean
有个特殊需求,一个普通的类,定时任务,需要获取SpringMVC的controller对应的bean: 方法: WebApplicationContext wac = ContextLoader.ge ...
- ajax的一些知识
一.关于XMLHttpRequest的实例的属性和方法 实例的属性: 1.xhr.response 响应主体内容 2.xhr.responseText 响应主体内容字符串(JSON或者XML格式字符串 ...
- XGBoost和LightGBM的参数以及调参
一.XGBoost参数解释 XGBoost的参数一共分为三类: 通用参数:宏观函数控制. Booster参数:控制每一步的booster(tree/regression).booster参数一般可以调 ...
- 201871010121 王方 《面向对象程序设计(JAVA)》第七周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...
- 用Jetpack的Site Accelerator为网站CDN加速
Jetpack 的Site Accelerator站点加速器(前身为 Photon,注意:“Photon”现在是站点加速器的一部分)允许 Jetpack 优化图像并通过他们的全球服务器网络CDN提供图 ...
- 莫烦TensorFlow_08 tensorboard可视化进阶
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # # add layer # def add_l ...
- Tomcat的下载和安装
登录Tomcat 站点,下载Tomcat最新版本http://tomcat.apache.org/Windows平台下载ZIP包,LInux平台下载TAR包,不建议下载安装文件,因为安装文件的 Tom ...
- LeetCode24-Swap_Pairs
swapPairs public ListNode swapPairs(ListNode head) { if(head==null ||head.next==null) return head; L ...
- LeetCode 51. N-QueensN皇后 (C++)(八皇后问题)
题目: The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two que ...
- 【day03】php
一.类型判别函数库 1.安装:类型判别函数库是PHPCORE的组成部分,不用安装 2. (1)is_integer|is_int|is_long 描述: 检测变量是否是整数 格式: ...