asp.net core 2.1 缓存和Session

缓存

缓存在内存中 ASP.NET Core

使用 IMemoryCache内存中缓存是使用依赖关系注入从应用中引用的服务。 请在ConfigureServices中调用AddMemoryCache():

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
 		services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseMvcWithDefaultRoute();
    }
}

在构造函数中请求 IMemoryCache实例:

public class HomeController : Controller
    {
        private IMemoryCache cache;

        public HomeController(IMemoryCache cache)
        {
             this.cache = cache;
        }

        public IActionResult Index()
        {
            cache.Set("name", $"shijia{DateTime.Now}", TimeSpan.FromSeconds(10));
            return View();
        }

        public IActionResult About()
        {
            object result;
            string value = cache.TryGetValue("name", out result) ? $"获取缓存name{result}" : "获取缓存失败";
            return Content(value);
        }

资料:https://docs.microsoft.com/zh-cn/aspnet/core/performance/caching/memory?view=aspnetcore-2.1#using-imemorycache

分布式缓存

https://docs.microsoft.com/zh-cn/aspnet/core/performance/caching/distributed?view=aspnetcore-2.1

Session

要添加对Session支持,否则会报错Session has not been configured for this
application or request。使用方法 http://www.cnblogs.com/sword-successful/p/6243841.html

(1)nuget安装Microsoft.AspNetCore.Session
(2) ConfigureServices中services.AddSession();
(3)Configure中app.UseSession();
(4)TempData依赖于Session,所以也要配置Session。
(5)HttpContext.Session,但是原始只有void Set(string key, byte[] value)bool TryGetValue(string key, out byte[] value)这两个方法。如果using Microsoft.AspNetCore.Http;(需要安装Microsoft.AspNetCore.Http.Extensions)还可以使用SessionExtensions中的值是int、string类型的,其他类型只能自己使用json进行序列化处理。
(6)推荐使用redis做进程外session:
http://www.hossambarakat.net/2016/02/03/configuring-redis-as-asp-net-core-1-0-session-store/

1.在MVC Controller里使用HttpContext.Session

using Microsoft.AspNetCore.Http;

public class HomeController:Controller
{
      public IActionResult Index()
      {
              HttpContext.Session.SetString("code","123456");
              return View();  
       }

       public IActionResult About()
       {
              ViewBag.Code=HttpContext.Session.GetString("code");
              return View();
        }
}

2.如果不是在Controller里,你可以注入IHttpContextAccessor

public class SomeOtherClass
{
      private readonly IHttpContextAccessor _httpContextAccessor;
      private ISession _session=> _httpContextAccessor.HttpContext.Session;

      public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
     {
           _httpContextAccessor=httpContextAccessor;              
     }

     public void Set()
     {
          _session.SetString("code","123456");
     }
    
     public void Get()
    {
         string code = _session.GetString("code");
     }
}

资料:ASP.NET Core 中的会话和应用状态
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1#session-state

问题:

Session 保存之后取不到值的解决方案

解决方案:
注释掉下面这段:

        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.AddMemoryCache();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSession();
        }
posted @ 2018-12-03 00:05  【唐】三三  阅读(1381)  评论(2编辑  收藏  举报