Redis 缓存无法与 Asp.net 核心一起使用



我尝试在核心应用程序中实现redis缓存 Asp.Net 但它没有在HttpContext.Session中设置任何值,甚至没有返回任何值。这是我的启动.cs文件。

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedRedisCache(options =>
        {
            options.InstanceName = Configuration.GetValue<string>("redis:name");
            options.Configuration = Configuration.GetValue<string>("redis:host");
        });
        services.AddSession(o=> { o.IdleTimeout = TimeSpan.FromMinutes(5); });  
        services.AddMvc();
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseSession();
        app.UseStaticFiles();

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

Appsetting.json

 "redis": {
"host": "redis-17930.c1.ap-southeast-1-1.ec2.cloud.redislabs.com",
"port": 17930,
"name": "Astroyogi"
  },

首页控制器.cs

   public IActionResult Index()
    {
        var helloRedis = Encoding.UTF8.GetBytes("Hello Redis");
        HttpContext.Session.Set("hellokey", helloRedis);
        var getHello = default(byte[]);
        HttpContext.Session.TryGetValue("hellokey", out getHello);
        ViewData["Hello"] = Encoding.UTF8.GetString(getHello);
       return View();
    }

和我安装的库-Microsoft.扩展.缓存.RedisMicrosoft.AspNetCore.Session

并且它不会在会话中设置任何值。请帮助我卡住的地方。

您不能在同一请求中同时设置和获取刚刚在Session中设置的值。会话需要设置 cookie,这只会在您返回响应后发生。在下一个请求中,您应该能够很好地访问您的值。

最新更新