ASP.NET Core MVC Redis实现Session共享 - Go语言中文社区

ASP.NET Core MVC Redis实现Session共享


环境:ASP.NET Core MVC,Redis-Win-x64-3.2.100


本文主要介绍在ASP.NET Core MVC中怎么利用Redis共享Session。

下面是操作步骤:

1、启动Redis服务器,就是让我们的Redis跑起来,具体参照https://blog.csdn.net/u012835032/article/details/115438693

2、要在ASP.NET Core MVC里面使用Redis,需要添加对Redis的引用,用NuGet就好了。

3、要用Session,需要在Startup.cs添加Session服务,指示Session保存的位置,这里是Redis。

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSession();

            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = "127.0.0.1:6379";
                options.InstanceName = "RedisTest";
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseSession();


            app.UseMvc(routes =>
            {
                routes.MapRoute(
                 name: "default",
                 template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

 4、在控制器里面用,直接调HttpContext.Session的Get和Set方法就行。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace RedisTest
{
    public class BaseController : Controller
    {
        protected string LoginUser
        {
            get
            {
                string user = HttpContext.Session.GetString("Login_User");
                if (string.IsNullOrWhiteSpace(user))
                {
                    user = "User0405";
                    HttpContext.Session.SetString("Login_User", user);
                }
                return user;
            }
            set
            {
                HttpContext.Session.SetString("Login_User", value);
            }
        }

    }
}

5、调试的时候可以看到sessionkey,在命令行可以看到Redis的keys,可以看到由Startup.cs配置Redis实例名和sessionkey组成的key。


Startup.cs全部代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace RedisTest
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.Configure<CookiePolicyOptions>(options =>
            //{
            //    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            //    options.CheckConsentNeeded = context => true;
            //    options.MinimumSameSitePolicy = SameSiteMode.None;
            //});

            //services.AddDistributedMemoryCache();
            services.AddSession();

            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = "127.0.0.1:6379";
                options.InstanceName = "RedisTest";
            });
            //password
            //services.AddDistributedRedisCache(options =>
            //{
            //    options.Configuration = "127.0.0.1:6379,password=123456,defaultdatabase=1";
            //    options.InstanceName = "RedisTest_";
            //});


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            

            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}
            //else
            //{
            //    app.UseExceptionHandler("/Error");
            //    app.UseHsts();
            //}

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();


            app.UseMvc(routes =>
            {
                routes.MapRoute(
                 name: "default",
                 template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/u012835032/article/details/115443710
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-13 13:42:40
  • 阅读 ( 1761 )
  • 分类:Redis

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢