Asp.net Core中动用Session

储存复杂对象

      存款和储蓄对象时把目的类别化成三个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>();

 

添加Session

     在您的档次上依据NuGet添加:Microsoft.AspNetCore.Session。

 

前言

      前年就那样悄无声息的启幕了,二零一七年对自笔者的话又是专门重大的一年。

      三朝放假在家写了个Asp.net Core验证码登录,
做demo的长河中相遇五个不是难点,第③是在Asp.net
Core中引用dll,现在我们引用DLL都是一向引用,在Core里那样是不行的,必须依照NuGet添加,或然依照project.json添加,然后保留VS会运维复苏类库。

其次就是行使Session的标题,Core里使用Session必要添加Session类库。

 

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

贰 、借使不是在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");
     }
}

 

 参考

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

修改startup.cs

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

    接下去大家要告知Asp.net
Core使用内部存款和储蓄器存款和储蓄Session数据,在Configure(IApplicationBuilder
app,…)中添加代码:app.UseSession();

 

相关文章