温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Session怎么在Asp.net Core项目中使用

发布时间:2021-03-30 17:57:06 来源:亿速云 阅读:323 作者:Leah 栏目:开发技术

这篇文章给大家介绍Session怎么在Asp.net Core项目中使用,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

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

关于Session怎么在Asp.net Core项目中使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI