Analyze how Asp.net uses Session

Y2J
Release: 2017-05-10 10:49:21
Original
1678 people have browsed it

Session is a method to save the session state of users and web applications. ASP.NET Core provides a middleware for managing session state. This article mainly introduces the use of Session in Asp.net Core. If you are interested You can find out more about it,

Preface

2017 started quietly, and 2017 is another particularly important year for me.

I wrote an Asp.net Core at home during the New Year's Day holidayVerification codeLog in. I encountered two small problems during the demo process. The first was to reference the dll in Asp.net Core. In the past, we referenced DLL directly. This is not possible in Core. It must be added based on NuGet, or added based on project.json, and then saving the VS will start to restore the class library.

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

Add Session

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

Modify startup.cs

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

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

Session

1. Use HttpContext.Session

#1 in

MVC

Controller. 2. If it is not in 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");
   }
}
Copy after login

Storage complex objects

Serialize the object into a json when storing the object StringStorage.

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);
  }
}
Copy after login
var myComplexObject = new MyClass();
HttpContext.Session.SetObjectAsJson("Test", myComplexObject);


var myComplexObject = HttpContext.Session.GetObjectFromJson<MyClass>("Test");
Copy after login

Use SQL Server or RedisStorage

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

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>();
Copy after login

[Related recommendations]

1.

ASP Free Video Tutorial

2.

ASP Tutorial

3.

Li Yanhui ASP basic video tutorial

The above is the detailed content of Analyze how Asp.net uses Session. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template