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(); //...... }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM