.NET Core Session的使用方法

刚使用.NET Core会不习惯,比如如何使用Session;不仅需要引用相应的类库,还需要在Startup.cs里进行注册。

1、在你的项目上基于NuGet添加:

install-package  Microsoft.AspNetCore.Session -ver 2.0

install-package Microsoft.AspNetCore.Http.Extensions -ver 2.0

2、在Startup.cs里进行注册

在Startup.cs文件中的ConfigureServices方法中添加:

services.AddSession();

在Startup.cs文件中的Configure方法中添加:

app.UseSession(); 

如果你看到这段文字,说明您正使用RSS阅读或转自《一棵树-博客园》,原文地址:https://www.cnblogs.com/atree/p/netcore-session.html 

添加后代码如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSession();
    services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    app.UseSession();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
    });
}

 3、在MVC Controller里使用HttpContext.Session

从nuget安装Microsoft.AspNetCore.Mvc引用,直接使用自带的方法进行设置和获取session。不过自带的方法设置和获取的session值是byte[]类型的,可以从nuget安装并引用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();
    }
}

 4、如果不是在Controller里,你可以注入IHttpContextAccessor

public class SessionTestClass
{
    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");
    }
}

5、Isession的扩展 存储复杂对象

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

 

posted on 2018-12-26 01:14  zock  阅读(9315)  评论(0编辑  收藏  举报