zoukankan      html  css  js  c++  java
  • 在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();
            }    
  • 相关阅读:
    uva 11995 I Can Guess the Data Structure!
    poj 1981 Circle and Points
    hdoj 2149 Public Sale
    hdoj 2188 悼念512汶川大地震遇难同胞——选拔志愿者
    hdoj 1846 Brave Game
    vue 细节注意
    meta标签设置不缓存
    -webkit-overflow-scrolling
    ios上表单默认样式
    vue-cli项目上传到github预览问题
  • 原文地址:https://www.cnblogs.com/nxhdw/p/7943469.html
Copyright © 2011-2022 走看看