Application State Options
---------------------------------------------------------------------
*HttpContext.Items
app.Use(async (context, next) =>
{
// perform some verification
context.Items["isVerified"] = true;
await next.Invoke();
}); app.Run(async (context) =>
{
await context.Response.WriteAsync("Verified request? " + context.Items["isVerified"]);
});
----------------------------------------------------------------------
*QueryString and Post
----------------------------------------------------------------------
*Cookies
----------------------------------------------------------------------
*Session
Microsoft.AspNetCore.Session
Microsoft.Extensions.Caching.Memory services.AddDistributedMemoryCache();
services.AddSession(); app.UseSession(); services.AddSession(options =>
{
options.CookieName = ".AdventureWorks.Session";
options.IdleTimeout = TimeSpan.FromSeconds();
}); {
services.AddDistributedMemoryCache(); services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds();
});
} // main catchall middleware
app.Run(async context =>
{
RequestEntryCollection collection = GetOrCreateEntries(context); if (collection.TotalCount() == )
{
await context.Response.WriteAsync("<html><body>");
await context.Response.WriteAsync("Your session has not been established.<br>");
await context.Response.WriteAsync(DateTime.Now.ToString() + "<br>");
await context.Response.WriteAsync("<a href=\"/session\">Establish session</a>.<br>");
}
else
{
collection.RecordRequest(context.Request.PathBase + context.Request.Path);
SaveEntries(context, collection); // Note: it's best to consistently perform all session access before writing anything to response
await context.Response.WriteAsync("<html><body>");
await context.Response.WriteAsync("Session Established At: " + context.Session.GetString("StartTime") + "<br>");
foreach (var entry in collection.Entries)
{
await context.Response.WriteAsync("Request: " + entry.Path + " was requested " + entry.Count + " times.<br />");
} await context.Response.WriteAsync("Your session was located, you've visited the site this many times: " + collection.TotalCount() + "<br />");
}
await context.Response.WriteAsync("<a href=\"/untracked\">Visit untracked part of application</a>.<br>");
await context.Response.WriteAsync("</body></html>");
}); public class RequestEntry
{
public string Path { get; set; }
public int Count { get; set; }
}
public class RequestEntryCollection
{
public List<RequestEntry> Entries { get; set; } = new List<RequestEntry>(); public void RecordRequest(string requestPath)
{
var existingEntry = Entries.FirstOrDefault(e => e.Path == requestPath);
if (existingEntry != null) { existingEntry.Count++; return; } var newEntry = new RequestEntry()
{
Path = requestPath,
Count =
};
Entries.Add(newEntry);
} public int TotalCount()
{
return Entries.Sum(e => e.Count);
}
} private RequestEntryCollection GetOrCreateEntries(HttpContext context)
{
RequestEntryCollection collection = null;
byte[] requestEntriesBytes = context.Session.Get("RequestEntries"); if (requestEntriesBytes != null && requestEntriesBytes.Length > )
{
string json = System.Text.Encoding.UTF8.GetString(requestEntriesBytes);
return JsonConvert.DeserializeObject<RequestEntryCollection>(json);
}
if (collection == null)
{
collection = new RequestEntryCollection();
}
return collection;
} // establish session
app.Map("/session", subApp =>
{
subApp.Run(async context =>
{
// uncomment the following line and delete session coookie to generate an error due to session access after response has begun
// await context.Response.WriteAsync("some content");
RequestEntryCollection collection = GetOrCreateEntries(context);
collection.RecordRequest(context.Request.PathBase + context.Request.Path);
SaveEntries(context, collection);
if (context.Session.GetString("StartTime") == null)
{
context.Session.SetString("StartTime", DateTime.Now.ToString());
} await context.Response.WriteAsync("<html><body>");
await context.Response.WriteAsync($"Counting: You have made {collection.TotalCount()} requests to this application.<br><a href=\"/\">Return</a>");
await context.Response.WriteAsync("</body></html>");
});
}); private void SaveEntries(HttpContext context, RequestEntryCollection collection)
{
string json = JsonConvert.SerializeObject(collection);
byte[] serializedResult = System.Text.Encoding.UTF8.GetBytes(json); context.Session.Set("RequestEntries", serializedResult);
} // example middleware that does not reference session at all and is configured before app.UseSession()
app.Map("/untracked", subApp =>
{
subApp.Run(async context =>
{
await context.Response.WriteAsync("<html><body>");
await context.Response.WriteAsync("Requested at: " + DateTime.Now.ToString("hh:mm:ss.ffff") + "<br>");
await context.Response.WriteAsync("This part of the application isn't referencing Session...<br><a href=\"/\">Return</a>");
await context.Response.WriteAsync("</body></html>");
});
}); app.UseSession();
----------------------------------------------------------------------
*Cache
-------------------------------------------------------------------
*Configuration

DotNet 学习笔记 应用状态管理的更多相关文章

  1. Linux内核学习笔记-2.进程管理

    原创文章,转载请注明:Linux内核学习笔记-2.进程管理) By Lucio.Yang 部分内容来自:Linux Kernel Development(Third Edition),Robert L ...

  2. linux kernel学习笔记-5内存管理_转

    void * kmalloc(size_t size, gfp_t gfp_mask); kmalloc()第一个参数是要分配的块的大小,第一个参数为分配标志,用于控制kmalloc()的行为. km ...

  3. Linux学习笔记(五) 账号管理

    1.用户与组账号 用户账号:包括实际人员和逻辑性对象(例如应用程序执行特定工作的账号) 每一个用户账号包含一个唯一的用户 ID 和组 ID 标准用户是系统安装过程中自动创建的用户账号,其中除 root ...

  4. Linux学习笔记(六) 进程管理

    1.进程基础 当输入一个命令时,shell 会同时启动一个进程,这种任务与进程分离的方式是 Linux 系统上重要的概念 每个执行的任务都称为进程,在每个进程启动时,系统都会给它指定一个唯一的 ID, ...

  5. Qt学习笔记-Widget布局管理

    Qt学习笔记4-Widget布局管理       以<C++ GUI Programming with Qt 4, Second Edition>为参考 实例:查找对话框 包含三个文件,f ...

  6. XV6学习笔记(2) :内存管理

    XV6学习笔记(2) :内存管理 在学习笔记1中,完成了对于pc启动和加载的过程.目前已经可以开始在c语言代码中运行了,而当前已经开启了分页模式,不过是两个4mb的大的内存页,而没有开启小的内存页.接 ...

  7. 操作系统学习笔记4 | CPU管理 && 多进程图像

    操作系统的核心功能就是管理计算机硬件,而CPU就是计算机中最核心的硬件.而通过学习笔记3的简史回顾,操作系统通过多进程图像实现对CPU的管理.所以多进程图像是操作系统的核心图像. 参考资料: 课程:哈 ...

  8. Vue.js 2.x笔记:状态管理Vuex(7)

    1. Vuex简介与安装 1.1 Vuex简介 Vuex是为vue.js应用程序开发的状态管理模式,解决的问题: ◊ 组件之间的传参,多层嵌套组件之间的传参以及各组件之间耦合度过高问题 ◊ 不同状态中 ...

  9. Adaptive AUTOSAR 学习笔记 10 - 执行管理

    本系列学习笔记基于 AUTOSAR Adaptive Platform 官方文档 R20-11 版本 AUTOSAR_EXP_PlatformDesign.pdf 缩写 EM:Execution Ma ...

随机推荐

  1. Android应用AsyncTask处理机制详解及源码分析

    1 背景 Android异步处理机制一直都是Android的一个核心,也是应用工程师面试的一个知识点.前面我们分析了Handler异步机制原理(不了解的可以阅读我的<Android异步消息处理机 ...

  2. [leetcode-636-Exclusive Time of Functions]

    Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find ...

  3. vue实战(一):利用vue与ajax实现增删改查

    vue实战(一):利用vue与ajax实现增删改查: <%@ page pageEncoding="UTF-8" language="java" %> ...

  4. 修改maven远程仓库为阿里的maven仓库(复制)

    maven之一:maven安装和eclipse集成 maven作为一个项目构建工具,在开发的过程中很受欢迎,可以帮助管理项目中的bao依赖问题,另外它的很多功能都极大的减少了开发的难度,下面来介绍ma ...

  5. linux系统基础文件属性

    记录用户登录前显示的信息 cat /etc/issue vim  /etc/motd    设置登录提醒 隐藏执行命令的历史记录用history –d  加上历史记录行号 如history -d 38 ...

  6. AndroidStudio3.0 注解报错Annotation processors must be explicitly declared now. The following dependencies on the compile classpath are found to contain annotation processor.

    体验最新版AndroidStudio3.0 Canary 8的时候,发现之前项目的butter knife报错,用到注解的应该都会报错 Error:Execution failed for task ...

  7. ActiveMQ+Zookeeper集群配置文档

    Zookeeper + ActiveMQ 集群整合配置文档 一:使用ZooKeeper实现的MasterSlave实现方式 是对ActiveMQ进行高可用的一种有效的解决方案, 高可用的原理:使用Zo ...

  8. (转)String,StringBuffer与StringBuilder的区别??

    String 字符串常量StringBuffer 字符串变量(线程安全)StringBuilder 字符串变量(非线程安全) 简要的说, String 类型和 StringBuffer 类型的主要性能 ...

  9. null?对象?异常?到底应该如何返回错误信息

    这篇文章记录我的一些思考.在工作了一段时间之后. 问题的核心很简单:到底如何返回错误信息. 学生时代,见到过当时的老师的代码: if (foo() == null) { } 当然,这位老师是一位比较擅 ...

  10. BZOJ1103 [POI2007]大都市meg 【树剖】

    1103: [POI2007]大都市meg Time Limit: 10 Sec  Memory Limit: 162 MB Submit: 3038  Solved: 1593 [Submit][S ...