在Asp.Net Core中使用Session

1.在Stratup.cs中配置Session

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddSession();
            services.AddMvc();           
        }
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseSession();//需在UseMvc语句前调用
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Login}/{action=Index}/{id?}");
            });
        }      
View Code

2.使用Session存储数据 

public IActionResult Index()
 {
    HttpContext.Session.SetString("Time",DateTime.Now.ToString());
    HttpContext.Session.GetString("Time");
     return View();
 }       

 3.如何使用Session存储一个实体对象

设置Session的扩展类

 public static class SessionExtension
    {
        public static void SetObject(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T GetObject<T>(this ISession session, string key)
        {
            var value = session.GetString(key);

            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }
    }

使用Session存储实体对象

 public IActionResult Index()
        {
            Person p = new Person();
            p.Name = "Master.V";
            p.Age = 18;
            HttpContext.Session.SetObject("PersonInfo", p);
            HttpContext.Session.GetObject<Person>("PersonInfo");
            return View();
        }    

 

posted @ 2017-12-01 17:16  Master.V  阅读(148)  评论(0编辑  收藏  举报