Resolving how ASP. NET uses session

Source: Internet
Author: User
The session is a way to save the conversation state of the user and the Web app, and ASP. NET core provides a middleware for managing session state, this article mainly introduces the use of sessions in ASP.

Objective

2017 was a silent start, and 2017 was a particularly important year for me.

New Year's Day holiday at home wrote an ASP. NET Core Verification code login, do the demo process encountered two small problems, the first is in the ASP. NET Core Reference DLL, in the past we reference DLLs are direct references, in the core this is not possible, must be based on NuGet added, or add based on Project.json, and then save vs will start the Restore class library.

The second is the use of the session, the core of the session need to add the Session class library.

Add session

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

Modify Startup.cs

In Startup.cs Find method Configureservices (iservicecollection services) to inject session (this place is ASP. NET Core Pipeline):services. Addsession ();

Next we'll tell ASP. NET core uses memory to store session data in Configure (Iapplicationbuilder app,...) Add code in: App. Usersession ();

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

Storing Complex objects

Serializes an object into a JSON string store when the object is stored.

public static class sessionextensions{public   static void Setobjectasjson (this isession session, string key, Object va Lue)  {    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");

Using SQL Server or Redis 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 D Atabase.services.AddSqlServerCache (o =>{  o.connectionstring = "server=.;D Atabase=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 would override any previously registered Idistributedcache Service.ser Vices. Addsingleton<idistributedcache, rediscache> ();

"Recommended"

1. asp free Video Tutorial

2. asp Tutorials

3. Eon the ASP Basic video tutorial

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.