1. 程式人生 > 實用技巧 >Asp.Net Core3.x中使用Cookie

Asp.Net Core3.x中使用Cookie

在Asp.Net中使用Cookie相對容易使用,Request和Response物件都提供了Cookies集合,要記住是從Response中儲存,從Request中讀取相應的cookie。Asp.Net Core3.x中Cookie相對不是直接使用,Asp.Net屬於大禮包方式把你要的不要的通通給你(比較臃腫_(¦3」∠)_),而在Asp.Net Core3.x中屬於自選行的專案中需要什麼自己引用什麼(比較清爽簡潔(#^.^#)),我們今天就說說在Asp.Net Core中如何使用Cookie。
一、在Asp.Net Core專案中Startup.cs中注入Cookie前置條件
在ConfigureServices方法中注入 services.AddHttpContextAccessor()方法 在Asp.Net Core3.x中HttpContext在介面IHttpContextAccessor中set、get 。
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

    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?}");
        });
    }
}

二、建立Cookie類
建立介面類ICookie
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);
    
}

要清楚知道在Asp.Net Core3.x中HttpContext在IHttpContextAccessor中。IHttpContextAccessor程式集引用Microsoft.AspNetCore.Http 專案下沒有的可以在NuGet包管理器中新增。
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;
    } 
}

三、在專案中使用Cookie 在HomeController我們直接使用IOC方式使用Cookie 當然要在Startup注入
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 });
    }
}

總結
1)、使用Cookie首先在Startup中注入AddHttpContextAccessor()
2)、建立Cookie公用類實現Cookie的增刪查
3)、專案中在Startup中注入Cookie在控制器中IOC方式使用Cookie