Redis缓存不适用于Asp.net核心

时间:2019-01-03 10:44:18

标签: asp.net-mvc asp.net-core redis

我尝试在Asp.Net Core应用程序中实现Redis缓存,但是它没有在HttpContext.Session中设置任何值,甚至没有返回任何值。这是我的startup.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"
  },

HomeController.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.Extensions.Caching.Redis Microsoft.AspNetCore.Session

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

1 个答案:

答案 0 :(得分:0)

在同一请求中,您不能同时设置和获取刚刚在Session中设置的值。会话需要设置一个cookie,只有在您返回响应后才会发生。在下一个请求时,您应该可以正常使用自己的值。