zoukankan      html  css  js  c++  java
  • Asp.net core如何使用Session

    转自:https://tahirnaushad.com/2017/08/18/asp-net-core-session-state/

    Asp.net core使用session:

    在nuget 安装Microsoft.AspNetCore.Session 

    在新建Asp.net core应用程序后,要使用session中间件,在startup.cs中需执行三个步骤:

    1.使用实现了IDistributedcache接口的服务来启用内存缓存。(例如使用内存缓存)

     //该步骤需在addsession()调用前使用。 

    2.调用addsession方法

    3.使用usesession回调(usesession需在useMvc()方法前调用)

     public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {
                    options.CheckConsentNeeded = context => false;  //注意这里需要设置为false,默认为true
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
                //注册数据库上下文
                services.AddDbContext<IgbomContext>();
                services.AddTransient<IRepository<Device>, DeviceRepository>();
                services.AddTransient<IRepository<User>, UserRepository>();
                services.AddTransient<IRepository<MenuRoot>, MenuRootRepository>();
                services.AddDistributedMemoryCache();
                services.AddSession();
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
            }
    
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    app.UseHsts();
                }
                app.UseSession();
                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseCookiePolicy();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    

      

    存储对象

    HttpContext.Session(实现了ISession接口)没有提供保存复杂对象的方法,然而我们可以通过序列化对象为字符串来实现这个功能:

    public static class SessionExtensions
    {
        public static void SetObject<T>(this ISession session, string key, T 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);
        }
    }
    

      

    JsonConvert是Newtonsoft.Json库的一个静态类,可以方便的在.Net类型和JSON类型之间转换,VS可以快速添加:

    接下来,我们就可以使用这些扩展方法:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseSession();
     
        app.Use(async (context, next) =>
        {
            context.Session.SetObject("CurrentUser",
                new UserInfo { Username = "James", Email = "james@bond.com" });
            await next();
        });
     
        app.Run(async (context) =>
        {
            var user = context.Session.GetObject<UserInfo>("CurrentUser");
            await context.Response.WriteAsync($"{user.Username}, {user.Email}");
        });
    }  
    

      

    通过依赖注入访问

    我们可以通过构造函数注入方式来使用会话状态(IHttpContextAccessor),然后通过这个接口来访问HttpContext属性。

  • 相关阅读:
    LeetCode--Sudoku Solver
    LeetCode--Merge Intervals
    LeetCode--Valid Number
    LeetCode--Max Points on a Line
    1.1
    智能指针原理与简单实现(转)
    C++内存管理(转)
    算法题--扔棋子
    LeetCode--Substring with Concatenation of All Words
    线性代数与MATALB1
  • 原文地址:https://www.cnblogs.com/xuqp/p/9204227.html
Copyright © 2011-2022 走看看