Session Introduction
This article assumes that the reader already understands the concept and role of the session and is used on traditional. NET Framework platforms.
ASP. NET core 1.0 seems to need to be installed separately, in the NuGet console, select your Web project to execute the following command:
Install-package Microsoft.AspNetCore.Session
If you need to uninstall, in the NuGet console, select the specific project and execute the following command:
Uninstall-package Microsoft.AspNetCore.Session
ASP. NET Core 2.0 has integrated the session components without having to be installed separately.
The session usage method in ASP. NET core is different from the traditional ASP. Two methods are built in for us to invoke:
void Set (stringbyte[] value); BOOL TryGetValue (stringbyte[] value);
The first parameter of both methods is key, the second parameter is value, and value is a byte[] type of data. So in the use of time, we also need to do the conversion, use is very inconvenient.
For this, the session provides an extension method, but you need to reference the Microsoft.AspNetCore.Http namespace. Then use the extension method:
byte string intstringstring string int string string value);
Here's how to use it:
HttpContext.Session.SetString ("password""123456 " = HttpContext.Session.GetString ("password");
Simple to use
Open Startup.cs File
1. In the Configureservices method, add:
Services. Addsession ();
2. In the Configure method, add:
App. Usesession ();
3. New controller Sessioncontroller, add the following code:
/// <summary> ///Test Session/// </summary> /// <returns></returns> PublicIactionresult Index () {varUsername ="Subendong"; varbytes =System.Text.Encoding.UTF8.GetBytes (username); HttpContext.Session.Set ("username", bytes); Byte[] bytestemp; HttpContext.Session.TryGetValue ("username", outbytestemp); varUsernametemp =System.Text.Encoding.UTF8.GetString (bytestemp); //use of extension methodsHttpContext.Session.SetString ("Password","123456"); varPassword = HttpContext.Session.GetString ("Password"); vardata =New{usernametemp, password}; returnJson (data); }
4.f5 Run, enter address: http://localhost/session, you can see the correct output:
{"Usernametemp": "Subendong", "Password": "123456"}
5. If the first and second steps do not do, the direct use of the session, will be error:
Invalidoperationexception:session have not been configured for this application or request
Using the ASP. NET Core Session