当前位置: 移动技术网 > IT编程>开发语言>.net > 解析Asp.net Core中使用Session的方法

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

爱上女主播分集介绍,马陵之战的交战双方是,社区动力

前言

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

using microsoft.aspnetcore.http;

public class homecontroller:controller
{
   public iactionresult index()
   {
       httpcontext.session.setstring("code","123456");
       return view(); 
    }

    public iactionresult about()
    {
       viewbag.code=httpcontext.session.getstring("code");
       return view();
    }
}

2、如果不是在controller里,你可以注入ihttpcontextaccessor

public class someotherclass
{
   private readonly ihttpcontextaccessor _httpcontextaccessor;
   private isession _session=> _httpcontextaccessor.httpcontext.session;

   public someotherclass(ihttpcontextaccessor httpcontextaccessor)
   {
      _httpcontextaccessor=httpcontextaccessor;       
   }

   public void set()
   {
     _session.setstring("code","123456");
   }
  
   public void get()
  {
     string code = _session.getstring("code");
   }
}

存储复杂对象

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

public static class sessionextensions
{
   public static void setobjectasjson(this isession session, string key, object value)
  {
    session.setstring(key, jsonconvert.serializeobject(value));
  }

  public static t getobjectfromjson<t>(this isession session, string key)
  {
    var value = session.getstring(key);

    return value == null ? default(t) : jsonconvert.deserializeobject<t>(value);
  }
}
var mycomplexobject = new myclass();
httpcontext.session.setobjectasjson("test", mycomplexobject);


var mycomplexobject = httpcontext.session.getobjectfromjson<myclass>("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<idistributedcache, rediscache>();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网