How to access the Session in ASP.NET Core via static variable?

前端 未结 3 1885
日久生厌
日久生厌 2020-12-16 20:27

In earlier version of Asp.Net session can be accessed in any page like a static variable using

System.Web.HttpContext.Current.Session[\"key\"]
3条回答
  •  情歌与酒
    2020-12-16 20:46

    In Startup.ConfigureServices you have to add the service

    services.AddSession();
    

    and in the method Configure you have to use it (important: call before app.UseMvc())

    app.UseSession();
    

    Now you can use it in your controllers (if derived from Controller). You can store

    var data = new byte[] { 1, 2, 3, 4 };
    HttpContext.Session.Set("key", data); // store byte array
    
    byte[] readData;
    HttpContext.Session.TryGetValue("key", out readData); // read from session
    

    When you import the namespace Microsoft.AspNetCore.Http then you can use SetString and SetInt32 as well.

    using Microsoft.AspNetCore.Http;
    
    HttpContext.Session.SetString("test", "data as string"); // store string
    HttpContext.Session.SetInt32("number", 4711); // store int
    
    int ? number = HttpContext.Session.GetInt32("number");
    

    Outside the controller you do not have access to the HttpContext, but you can inject an IHttpContextAccessor instance like described in this answer

提交回复
热议问题