Use Session and coresession in Asp.net Core

Source: Internet
Author: User

Use Session and coresession in Asp.net Core
Preface

In, it was a very important year for me.

During the New Year's Day holiday, I wrote an Asp.net Core verification code at home to log on. During the demo process, I encountered two minor problems. The first problem was to reference dll in Asp.net Core. In the past, we referenced DLL directly, this cannot be done in Core. It must be added based on NuGet or project. add json, and then save VS to start restoring the class library.

The second is to use the Session. To use the Session in the Core, you need to add the Session class library.

 

Add Session

Add Microsoft. AspNetCore. Session in your project based on NuGet.

 

Modify startup. cs

Find ConfigureServices (IServiceCollection services) in startup. cs to inject Session (this is Asp.net Core pipeline): services. AddSession ();

Next we will tell Asp.net Core to use memory to store Session data, and add the code: app. UserSession () in Configure (IApplicationBuilder app ();

 

Session

1. Use HttpContext. Session in MVC Controller

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. If it is not in the Controller, You can inject 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");     }}

 

Store complex objects

Serialize an object into a json string for storage.

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

 

Use SQL Server or Redis for storage

1. SQL Server

Add reference"Microsoft.Extensions.Caching.SqlServer": "1.0.0"

Injection:

// 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

Add reference"Microsoft.Extensions.Caching.Redis": "1.0.0"

Injection:

// Redis implementation of IDistributedCache.// This will override any previously registered IDistributedCache service.services.AddSingleton<IDistributedCache, RedisCache>();

 

Reference

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.