剑轩

.net core 使用session

电脑版发表于:2018/12/18 17:04


tip:net core 2.2后可以直接启用session了,不用在自己添加一次session依赖,本身就添加了


使用nuget 添加引用 Microsoft.AspNetCore.Session 

在nuget中执行命令 :Install-Package Microsoft.AspNetCore.Session


更新 Startup.cs 使用需要的服务

public void ConfigureServices(IServiceCollection services)
{       
   services.AddSession();
   services.AddMvc(); 
}

在Configure中启用session

app.UseSession();


 注意:当添加完Microsoft.AspNetCore.Session依赖后很有可能在写 app.UseSession()

     与services.AddSession()的时候会报错



其实生成是可以生成成功的,因为才添加了引用vs的智能提示还没反应过来,关闭重新运行一下就可以了



然后使用session

 存:

HttpContext.Session.SetString("username","xx");

取:

 string username = HttpContext.Session.GetString("username");


tip: 以前session中可以直接保存对象,这里还不行


tip:要使用SetString方法,需要引用using Microsoft.AspNetCore.Http


super tip:如果要存储对象从使用json序列化吧.......

http://www.tnblog.net/aojiancc2/article/details/2438

big super tip:估计是因为net core要扩平台所用不支持直接存储对象,而存储字符串吧.......





关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢