NET 5 Session、Cookie和Cache的使用
1.Cookie
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.AddHttpContextAccessor();//配置Cookie HttpContext services.AddTransient<ICookie, Cookie>();//IOC配置 方便项目中使用 services.AddTransient(typeof(Config));//基础配置 } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Index"); // 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.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } }
public interface ICookie { void SetCookies(string key, string value, int minutes = 300); /// <summary> /// 删除指定的cookie /// </summary> /// <param name="key">键</param> void DeleteCookies(string key); /// <summary> /// 获取cookies /// </summary> /// <param name="key">键</param> /// <returns>返回对应的值</returns> string GetCookies(string key); }
public class Cookie : ICookie { private readonly IHttpContextAccessor _httpContextAccessor; public Cookie(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } /// <summary> /// 设置本地cookie /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="minutes">过期时长,单位:分钟</param> public void SetCookies(string key, string value, int minutes = 300) { _httpContextAccessor.HttpContext.Response.Cookies.Append(key, value, new CookieOptions { Expires = DateTime.Now.AddMinutes(minutes) }); } /// <summary> /// 删除指定的cookie /// </summary> /// <param name="key">键</param> public void DeleteCookies(string key) { _httpContextAccessor.HttpContext.Response.Cookies.Delete(key); } /// <summary> /// 获取cookies /// </summary> /// <param name="key">键</param> /// <returns>返回对应的值</returns> public string GetCookies(string key) { _httpContextAccessor.HttpContext.Request.Cookies.TryGetValue(key, out string value); if (string.IsNullOrEmpty(value)) value = string.Empty; return value; } }
public class HomeController : Controller { private readonly ILogger _logger; private readonly ICookie _cookie; private readonly Config _config; public HomeController(ILogger<HomeController> logger, ICookie cookie, Config config) { _logger = logger; this._cookie = cookie; this._config = config; } public IActionResult Index() { _cookie.SetCookies(_config.CookieName(), "CookieValue"); string CookieValue = _cookie.GetCookies(_config.CookieName()); _cookie.DeleteCookies(_config.CookieName()); return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } }
2.Session
在你的项目上基于NuGet添加
Microsoft.AspNetCore.Session
在startup.cs找到方法ConfigureServices(IServiceCollection services) 注入Session
services.AddSession();
app.UseSession();
在控制器中设置和使用session
//写入session HttpContext.Session.SetInt32("userId", 10);
//获取session
3.Cache
1 public void ConfigureServices(IServiceCollection services) 2 { 3 services.AddMemoryCache(); 4 }
1 public class LoginController : Controller 2 { 3 private IMemoryCache _cache; 4 5 public LoginController(IMemoryCache memoryCache) 6 { 7 _cache = memoryCache; 8 }
1 //检查用户名是否存在 2 public JsonResult SelectUName(string uname) 3 { 4 //读取缓存 5 var cache = _cache.Get("re_" + uname); 6 if (cache == null)//如果没有该缓存 7 { 8 //查询用户名是否存在 9 var re = _userdal.SelectUName(uname); 10 //将验证结果添加到缓存 11 _cache.Set("re_" + uname, re.Status, new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(10))); 12 return Json(new { status = re.Status }); 13 } 14 else//如果缓存不为空,则返回缓存内容 15 { 16 return Json(new { status = cache }); 17 } 18 }
1 //删除 2 public int Delete(int uid) 3 { 4 var re = _maindal.Delete(uid); 5 //删除成功之后移除验证用户名缓存 6 _cache.Remove("re_" + HttpContext.Session.GetString("name")); 7 return re; 8 }
Session缓存和Cache缓存的区别如下:
(1)最大的区别是Cache提供缓存依赖来更新数据,而Session只能依靠定义的缓存时间来判断缓存数据是否有效。
(2)即使应用程序终止,只要Cache.Add方法中定义的缓存时间未过期,下次开启应用程序时,缓存的数据依然存在。而Session缓存只是存在于一次会话中,会话结束后,数据也就失效了。
(3)Session容易丢失,导致数据的不确定性,而Cache不会出现这种情况。
(4)由于Session是每次会话就被加载,所以不适宜存放大量信息,否则会导致服务器的性能降低。而Cache则主要用来保存大容量信息,如数据库中的多个表。
需要特别注意:为了提高Cache的有效利用率,建议对于不经常改动的数据使用Cache。
public void ConfigureServices(IServiceCollection services)
{
//如何处理session
services.AddSession();
//memoryCache
services.AddMemoryCache();
//.......
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//启用session
app.UseSession();
app.UseRouting();
//......
}