• ASP.NET Core 使用Redis存储Session


    首先创建ASP.NET CORE Web项目,然后按如下顺序操作。

    1.添加nuget程序包:

    Microsoft.AspNetCore.Session;
    Microsoft.AspNetCore.DataProtection.Redis;
    Microsoft.Extensions.Caching.Redis.Core;
    Microsoft.AspNetCore.Http;     //使用Session时有扩展方法

    2.在appsettings.json中添加Redis配置:

     1 {
     2   "Logging": {
     3     "IncludeScopes": false,
     4     "LogLevel": {
     5       "Default": "Warning"
     6     }
     7   },
     8   "WebConfig": {
     9     "Redis": {
    10       "Connection": "127.0.0.1:6379,allowAdmin=true,password=123456,defaultdatabase=5",
    11       "InstanceName": "Test_Redis_Session_"
    12     },
    13     "SessionTimeOut": "30" //session过期时长,分钟
    14   }
    15 }

     3.在startup.cs类中,按如下例子添加代码:

     1         // This method gets called by the runtime. Use this method to add services to the container.
     2         public void ConfigureServices(IServiceCollection services)
     3         {
     4             // Add framework services.
     5             services.AddMvc();
     6 
     7             #region 使用Redis保存Session
     8             var redisConn = Configuration["WebConfig:Redis:Connection"];
     9             var redisInstanceName = Configuration["WebConfig:Redis:InstanceName"];
    10             //Session 过期时长分钟
    11             var sessionOutTime = Configuration.GetValue<int>("WebConfig:SessionTimeOut", 30);
    12 
    13             var redis = StackExchange.Redis.ConnectionMultiplexer.Connect(redisConn);
    14             services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Test-Keys");
    15             services.AddDistributedRedisCache(option =>
    16             {
    17                 //redis 连接字符串
    18                 option.Configuration = redisConn;
    19                 //redis 实例名
    20                 option.InstanceName = redisInstanceName;
    21             }
    22             );
    23             #endregion
    24 
    25             //添加Session并设置过期时长
    26             services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(sessionOutTime); });
    27         }
    28 
    29         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    30         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    31         {
    32             loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    33             loggerFactory.AddDebug();
    34 
    35 
    36             app.UseSession();
    37 
    38             if (env.IsDevelopment())
    39             {
    40                 app.UseDeveloperExceptionPage();
    41                 app.UseBrowserLink();
    42             }
    43             else
    44             {
    45                 app.UseExceptionHandler("/Home/Error");
    46             }
    47 
    48             app.UseStaticFiles();
    49 
    50             app.UseMvc(routes =>
    51             {
    52                 routes.MapRoute(
    53                     name: "default",
    54                     template: "{controller=Home}/{action=Index}/{id?}");
    55             });
    56         }

    4.在控制器HomeController中添加:

     1     public class HomeController : Controller
     2     {
     3         public IActionResult Index()
     4         {
     5             ViewData["UserName"] = this.HttpContext.Session.GetString("UserName");
     6             ViewData["PassWord"] = this.HttpContext.Session.GetString("PassWord");
     7             return View();
     8         }
     9 
    10 
    11         [HttpPost]
    12         public NoContentResult Add(string userName,string pwd)
    13         {
    14             this.HttpContext.Session.SetString("UserName", userName);
    15 
    16             this.HttpContext.Session.SetString("PassWord", pwd);
    17 
    18             return NoContent();
    19         }

    5.在View/Index.cshtml添加如下代码:

     1     …………
     2 <form method="post" action="../Home/Add">
     3     <div>
     4         <input name="username" id="username" type="text" value="@ViewData["UserName"]" />
     5         <input name="pwd" id="pwd" type="password" value="" />
     6         <input type="submit" value="更新" />
     7         <h1>提交用户名称为:@ViewData["UserName"]    密码:@ViewData["PassWord"]</h1>
     8         <a href="javascript:void(0);" onclick="window.location.reload();">刷新显示最新值</a>
     9     </div>
    10 </form>
    11   …………

    6.下载Demo




  • 相关阅读:
    关于hive开窗函数的问题
    MFC三种不同方式实现图形的保存和重绘---方法一:通过集合类CPtrArray保存点的坐标
    win8 安装VC++ 6.0 出现错误的解决方法
    在数组中进行二分查找找出某数在数组中的下标
    编写自定义的字符串一致性匹配方法,只要两个字符串包含同样的字符, 不管字符的顺序如何,都认为两个字符串一致,如:”aabbcc”和”abcabc”被认为是一致的
    若干个数 以“字符串形式‘从键盘输入,将其转换为 double 型,并求平均数
    使用IO技术,创建一个目录,然后复制一个文件到该目录!实现复制的功能。(在博客园上传的第一份代码)
    easyui datagrid editor可选type
    MVC统计在线人数
    替换SQL字段中的换行符,回车符
  • 原文地址:https://www.cnblogs.com/shouwu/p/6180652.html
Copyright © 2020-2023  润新知