使用Redis缓存作为会话存储asp.net核心

时间:2018-12-12 12:33:53

标签: c# session caching redis asp.net-core-mvc

尝试将Redis缓存用作在asp.net mvc core(2.1.1)中开发的现有Web应用程序中的会话存储。

指的是https://garywoodfine.com/redis-inmemory-cache-asp-net-mvc-core/

https://joonasw.net/view/redis-cache-session-store,但是在尝试在Redis Desktop Manager中检查会话设置/获取值时,没有显示任何内容。

要使会话存储区使用Redis缓存而不是默认的内存(进程内)选项,是否需要采取其他步骤?

Startup.cs

node.exe

设置

    public void ConfigureServices(IServiceCollection services)
     {
      services.AddDistributedRedisCache(options =>
            {
                options.InstanceName = Configuration.GetValue<string> 
                          ("redis:name");
                options.Configuration = Configuration.GetValue<string> 
                                           ("redis:host");

              });

             services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddSessionStateTempDataProvider();
             services.AddSingleton<IDistributedCache, RedisCache>();

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

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();

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

使用了Nuget软件包

Microsoft.Extensions.Caching.Redis 2.1.1

示例使用方式

 "redis": {
    "host": "127.0.0.1",
    "port": 6379,
    "name": "localhost"
  },

赞赏任何与此有关的指针或方向。

TIA

1 个答案:

答案 0 :(得分:1)

检查此:

//Shared Session in RedisCache

using StackExchange.Redis;
using Microsoft.AspNetCore.DataProtection;

      public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddDataProtection()
                .SetApplicationName("vextus")
                .PersistKeysToRedis(ConnectionMultiplexer.Connect(Configuration.GetConnectionString("RedisConnection")),
                                    "DataProtection-Keys");


            services.AddDistributedRedisCache(o =>
            {
                o.Configuration = Configuration.GetConnectionString("RedisConnection");
            });

            services.AddSession(o =>
            {
                o.Cookie.Name = "vextus";
                o.Cookie.SameSite = SameSiteMode.None;
                o.Cookie.HttpOnly = true;
                o.IdleTimeout = TimeSpan.FromMinutes(10);
            });
        }