Asp.net Core中采用Session

前言

      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.UseSession();

 

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>();

 

 参考

http://benjii.me/2016/07/using-sessions-and-httpcontext-in-aspnetcore-and-mvc-core/

相关文章