解析aspx|解析Asp.net Core中使用Session的方法

更新时间:2021-05-17    来源:元旦    手机版     字体:

【www.bbyears.com--元旦】

前言

2017年就这么悄无声息的开始了,2017年对我来说又是特别重要的一年。

元旦放假在家写了个Asp.net Core验证码登录, 做demo的过程中遇到两个小问题,第一是在Asp.net Core中引用dll,以往我们引用DLL都是直接引用,在Core里这样是不行的,必须基于NuGet添加,或者基于project.json添加,然后保存VS会启动还原类库。

第二就是使用Session的问题,Core里使用Session需要添加Session类库。

添加Session

在你的项目上基于NuGet添加:Microsoft.AspNetCore.Session。

修改startup.cs

在startup.cs找到方法ConfigureServices(IServiceCollection services) 注入Session(这个地方是Asp.net Core pipeline):services.AddSession();

接下来我们要告诉Asp.net Core使用内存存储Session数据,在Configure(IApplicationBuilder app,...)中添加代码:app.UserSession(); 

Session

1、在MVC Controller里使用HttpContext.Session

   代码如下 usingMicrosoft.AspNetCore.Http;   publicclassHomeController:Controller {    publicIActionResult Index()    {        HttpContext.Session.SetString("code","123456");        returnView();     }       publicIActionResult About()     {        ViewBag.Code=HttpContext.Session.GetString("code");        returnView();     } }  

2、如果不是在Controller里,你可以注入IHttpContextAccessor

   代码如下 publicclassSomeOtherClass {    privatereadonlyIHttpContextAccessor _httpContextAccessor;    privateISession _session=> _httpContextAccessor.HttpContext.Session;      publicSomeOtherClass(IHttpContextAccessor httpContextAccessor)    {       _httpContextAccessor=httpContextAccessor;          }      publicvoidSet()    {      _session.SetString("code","123456");    }        publicvoidGet()   {      stringcode = _session.GetString("code");    } }  

存储复杂对象

存储对象时把对象序列化成一个json字符串存储。

   代码如下 publicstaticclassSessionExtensions {    publicstaticvoidSetObjectAsJson(thisISession session,stringkey,objectvalue)   {     session.SetString(key, JsonConvert.SerializeObject(value));   }     publicstaticT GetObjectFromJson(thisISession session,stringkey)   {     var value = session.GetString(key);       returnvalue ==null?default(T) : JsonConvert.DeserializeObject(value);   } } var myComplexObject =newMyClass(); HttpContext.Session.SetObjectAsJson("Test", myComplexObject);     var myComplexObject = HttpContext.Session.GetObjectFromJson("Test");  

使用SQL Server或Redis存储

1、SQL Server

添加引用  "Microsoft.Extensions.Caching.SqlServer": "1.0.0"

注入:

   代码如下 // Microsoft SQL Server implementation of IDistributedCache. // Note that this would require setting up the session state database. services.AddSqlServerCache(o => {   o.ConnectionString ="Server=.;Database=ASPNET5SessionState;Trusted_Connection=True;";   o.SchemaName ="dbo";   o.TableName ="Sessions"; });  

2、Redis

添加引用   "Microsoft.Extensions.Caching.Redis": "1.0.0"

注入:

   代码如下 // Redis implementation of IDistributedCache. // This will override any previously registered IDistributedCache service. services.AddSingleton();  

本文来源:http://www.bbyears.com/zhufuduanxin/118053.html

猜你感兴趣

热门标签

更多>>

本类排行