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<HomeController> _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

posted @ 2020-09-03 15:47  Seven`  阅读(869)  评论(0编辑  收藏  举报