首页 > 分享 > ASP.NET Core 使用Redis存储Session

ASP.NET Core 使用Redis存储Session

https://www.cnblogs.com/shouwu/p/6180652.html

首先创建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配置:

{

"Logging": {

"IncludeScopes": false,

"LogLevel": {

"Default": "Warning"

}

},

"WebConfig": {

"Redis": {

"Connection": "127.0.0.1:6379,allowAdmin=true,password=123456,defaultdatabase=5",

"InstanceName": "Test_Redis_Session_"

},

"SessionTimeOut": "30" //session过期时长,分钟

}

}

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

// This method gets called by the runtime. Use this method to add services to the container.

public void ConfigureServices(IServiceCollection services)

{

// Add framework services.

services.AddMvc();

#region 使用Redis保存Session

var redisConn = Configuration["WebConfig:Redis:Connection"];

var redisInstanceName = Configuration["WebConfig:Redis:InstanceName"];

//Session 过期时长分钟

var sessionOutTime = Configuration.GetValue<int>("WebConfig:SessionTimeOut", 30);

var redis = StackExchange.Redis.ConnectionMultiplexer.Connect(redisConn);

services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Test-Keys");

services.AddDistributedRedisCache(option =>

{

//redis 连接字符串

option.Configuration = redisConn;

//redis 实例名

option.InstanceName = redisInstanceName;

}

);

#endregion

//添加Session并设置过期时长

services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(sessionOutTime); });

}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

{

loggerFactory.AddConsole(Configuration.GetSection("Logging"));

loggerFactory.AddDebug();

app.UseSession();

if (env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

app.UseBrowserLink();

}

else

{

app.UseExceptionHandler("/Home/Error");

}

app.UseStaticFiles();

app.UseMvc(routes =>

{

routes.MapRoute(

name: "default",

template: "{controller=Home}/{action=Index}/{id?}");

});

}

4.在控制器HomeController中添加:

public class HomeController : Controller

{

public IActionResult Index()

{

ViewData["UserName"] = this.HttpContext.Session.GetString("UserName");

ViewData["PassWord"] = this.HttpContext.Session.GetString("PassWord");

return View();

}

[HttpPost]

public NoContentResult Add(string userName,string pwd)

{

this.HttpContext.Session.SetString("UserName", userName);

this.HttpContext.Session.SetString("PassWord", pwd);

return NoContent();

}

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

…………

<form method="post" action="../Home/Add">

<div>

<input name="username" id="username" type="text" value="@ViewData["UserName"]" />

<input name="pwd" id="pwd" type="password" value="" />

<input type="submit" value="更新" />

<h1>提交用户名称为:@ViewData["UserName"] 密码:@ViewData["PassWord"]</h1>

<a href="javascript:void(0);" onclick="window.location.reload();">刷新显示最新值</a>

</div>

</form>

…………

相关知识

Linux跨平台部署DotNetCore记录
《工作碰上的技术问题及处理经验》(五)
Ef Core花里胡哨系列(11) ef8 无实体查询,你好!
基于ASP.NET的植物病虫害远程诊断咨询系统
ASP.NET网上鲜花销售系统的设计
js上传文件带参数,并且,返回给前台文件路径,解析上传的xml文件,存储到数据库中
SDL:安全性非功能需求识别表
plsql连接oracle模糊查询中文不成功
基于springboot实现的对人社区交流平台(计算机毕设交流案例)
Roses double core candle wedding decorations 中文翻译英文意思,翻译英语

网址: ASP.NET Core 使用Redis存储Session https://m.huajiangbk.com/newsview547568.html

所属分类:花卉
上一篇: 积分当钱花
下一篇: AFNetWorking3.1