Sessions can be either in memory or stored in a database,. NET core provides the configuration stored in the database
First, we need to generate the session database by CMD instruction, and generate database field Id,value,expiresattime,
Slidingexpirationinseconds,absoluteexpiration
Second, the session configuration:
(1) Startup.cs file, find Configureservices (iservicecollection Services) method injection session,
//sessiondb
services. Adddistributedsqlservercache (o =>
{
o.connectionstring = "server=10.1.1.10;database=aaaaa;uid=sa;pwd= P@ssw0rd; ";
O.schemaname = "dbo";
O.tablename = "sessionstate";
});
SESSIONB Timeout
Services. Addsession (o =>
{
o.idletimeout = timespan.fromseconds (1800);
});
(2) Find Configure method, inject session
//sessiondb
app. Usesession ();
Then we can use the session in the Controller.
HttpContext.Session.SetString ("Code", "123456");
HttpContext.Session.GetString ("code");
Note: The injection prompts some packages to be introduced, and the code can download the NUT package to the project by means of a tool.
Microsoft.AspNetCore.Session.
But the core session is limited to controller and wants to be used elsewhere, and ihttpcontextaccessor annotations are needed.
Httpcontextaccessor annotations are first made in the Startup.cs file in the configureservices (Iservicecollection Services) method.
Services. Tryaddsingleton<ihttpcontextaccessor, httpcontextaccessor> ();
Second, find the Configure method, add IServiceProvider SVP parameters, add "Myhttpcontext.serviceprovider = SVP to the method".
After the injection in the custom Myhttpcontext class
public static class Myhttpcontext
{public
static IServiceProvider serviceprovider;
Static Myhttpcontext ()
{} public
static HttpContext current
{
get
{
Object factory = Serviceprovider.getservice (typeof (Microsoft.AspNetCore.Http.IHttpContextAccessor));
HttpContext context = ((Ihttpcontextaccessor) factory). HttpContext;
return context;
}
}
}
Note: If you add a class in a Framework class library, you need to introduce
Microsoft.AspNetCore.Html.Abstractions.DLL
Microsoft.AspNetCore.Http.DLL
Microsoft.AspNetCore.Http.Abstractions.DLL
When used MyHttpContext.Current.Session.SetString ("code", "123456");
MyHttpContext.Current.Session.GetString ("code");
Note: If an error is used in another class library, it is also necessary to introduce
Microsoft.AspNetCore.Http.DLL
Microsoft.AspNetCore.Http.Abstractions.DLL
Microsoft.AspNetCore.Http.Extensions.DLL
Microsoft.AspNetCore.Http.Features.DLL
Microsoft.AspNetCore.HttpOverrides.DLL
Friendly tip: Seivice class of injection: services. Addtransient<isitecontract, siteservice> ();