前端之家收集整理的这篇文章主要介绍了
[asp.net core 源码分析] 01 - Session,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
1、Session文档介绍
- 毋庸置疑学习.Net core最好的方法之一就是学习微软.Net core的官方文档;;
- .Net core Session的官方文档
- .Net core Session Github源码
2、Session简单应用
2.1、在Startup类的ConfigureServices方法中添加
因为Session的服务端存储需要缓存,所以需要引入.Net core的缓存DistributedMemoryCache;
2.2、在Startup类的Configure方法中添加
app.UseSession();
2.3、使用(存储和获取)
HttpContext.Session.Set(,System.Text.Encoding.Default.GetBytes(<span style="color: #008000;">//<span style="color: #008000;"> 获取
HttpContext.Session.TryGetValue(<span style="color: #800000;">"<span style="color: #800000;">LoginId<span style="color: #800000;">",<span style="color: #0000ff;">out <span style="color: #0000ff;">byte<span style="color: #000000;">[] byteLoginId);
<span style="color: #0000ff;">var loginId = System.Text.Encoding.Default.GetString(byteLoginId); // LoginId="666";
3、源码分析图

4、源码分析
4.1、程序加载
4.1.1、在ConfigureServices中添加分布式缓存,services.AddDistributedMemoryCache();
微软官方建议使用AddDistributedMemoryCache,当然也可以使用AddDistributedRedisCache、AddDistributedSqlServerCache或者自定义缓存也是可以的;
如果是分布式系统或者SSO单点登录,建议使用分布式的缓存AddDistributedRedisCache,AddDistributedSqlServerCache;
缓存的官方文档
4.1.2、在ConfigureServices中添加AddSession;
IServiceCollection AddSession( (services ==
services.AddTransient
IServiceCollection AddSession( IServiceCollection services,Action (services ==
(configure ==
}
403-0f87-4db0-b848-bedfbe5d6c5d')">
![]()
403-0f87-4db0-b848-bedfbe5d6c5d" class="code_img_closed" src="/res/2019/02-07/23/1c53668bcee393edac0d7b3b3daff1ae.gif" alt="">
![]()
403-0f87-4db0-b848-bedfbe5d6c5d" class="code_img_opened" style="display: none;" onclick="cnblogs_code_hide('68b8b
403-0f87-4db0-b848-bedfbe5d6c5d',event)" src="/res/2019/02-07/23/405b18b4b6584ae338e0f6ecaf736533.gif" alt="">
403-0f87-4db0-b848-bedfbe5d6c5d" class="cnblogs_code_hide">
IApplicationBuilder UseSession( (app ==
app.UseMiddleware
IApplicationBuilder UseSession( (app == (options ==
app.UseMiddleware }