Home >Backend Development >C#.Net Tutorial >Introducing the method of using Session in Asp.net

Introducing the method of using Session in Asp.net

Y2J
Y2JOriginal
2017-05-16 10:02:562066browse

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 learn 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 based on project.json. Then saving VS will start restoring 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

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

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

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

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

[Related recommendations]

1.

Special recommendation:"php programmer toolbox ”V0.1 version download

2.

ASP free video tutorial

3.

asp reference manual

The above is the detailed content of Introducing the method of using Session in Asp.net. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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