ASP.NET Core 3.1系列(9)——Cookie的相关操作

32 篇文章 43 订阅

1、前言

Cookie通常用来存储有关用户信息的一条数据,它可以用来标识登录用户,一般存储在客户端的浏览器上。在大多数浏览器中,每个Cookie都被存储为一个小文件,它一般采用键/值对的形式进行描述,因此可以利用键来读取、写入或删除Cookie。下面就来看看如何在ASP.NET Core中进行Cookie的设置、读取、删除操作。

2、在Controller中操作Cookie

如果是在Controller中直接操作Cookie,则直接使用如下两个组件即可:

  • HttpContext.Response.Cookies:设置、删除Cookie
  • HttpContext.Request.Cookies:获取Cookie

2.1、设置Cookie

设置Cookie的代码如下:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;

namespace App.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        [HttpGet]
        public ActionResult<string> SetCookie()
        {
            try
            {
                CookieOptions options = new CookieOptions
                {
                    Expires = DateTime.Now.AddDays(1)
                };
                HttpContext.Response.Cookies.Append("UserName", "admin", options);
                HttpContext.Response.Cookies.Append("Password", "12345", options);
                return Ok("添加Cookie成功");
            }
            catch
            {
                return BadRequest("添加Cookie失败");
            }
        }
    }
}

运行结果如下图所示:
在这里插入图片描述

2.2、获取Cookie

获取Cookie的代码如下:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace App.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        [HttpGet]
        public ActionResult<string> GetCookie()
        {
            try
            {
                return HttpContext.Request.Cookies["UserName"] + "\n" +
                       HttpContext.Request.Cookies["Password"];
            }
            catch
            {
                return BadRequest("获取Cookie失败");
            }
        }
    }
}

运行结果如下图所示:
在这里插入图片描述

2.3、删除Cookie

删除Cookie的代码如下:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace App.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        [HttpGet]
        public ActionResult<string> DeleteCookie()
        {
            try
            {
                HttpContext.Response.Cookies.Delete("UserName");
                HttpContext.Response.Cookies.Delete("Password");
                return Ok("删除Cookie成功");
            }
            catch
            {
                return BadRequest("删除Cookie失败");
            }
        }
    }
}

运行结果如下图所示:
在这里插入图片描述

3、封装Cookie操作类

如果我们要将Cookie的相关操作封装成类又该怎么办呢?在上面的代码中,我们主要是用HttpContextCookie进行操作,但HttpContextControllerBase的一个属性,我们定义的操作类难道要继承它吗?
在这里插入图片描述
ASP.NET Core中,如果想使用HttpContext属性,我们可以注入IHttpContextAccessor接口,首先创建一个接口文件ICookieHelper,代码如下:

namespace App
{
    public interface ICookieHelper
    {
        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        void SetCookie(string key, string value);

        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expires">失效时间</param>
        void SetCookie(string key, string value, int expires);

        /// <summary>
        /// 获取Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>Cookie值</returns>
        string GetCookie(string key);

        /// <summary>
        /// 删除Cookie
        /// </summary>
        /// <param name="key">键</param>
        void DeleteCookie(string key);
    }
}

然后创建一个CookieHelper实现ICookieHelper,代码如下:

using Microsoft.AspNetCore.Http;
using System;

namespace App
{
    public class CookieHelper : ICookieHelper
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        public CookieHelper(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public void SetCookie(string key, string value)
        {
            httpContextAccessor.HttpContext.Response.Cookies.Append(key, value);
        }

        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expires">失效时间</param>
        public void SetCookie(string key, string value, int expires)
        {
            CookieOptions options = new CookieOptions()
            {
                Expires = DateTime.Now.AddDays(expires)
            };
            httpContextAccessor.HttpContext.Response.Cookies.Append(key, value, options);
        }

        /// <summary>
        /// 获取Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>Cookie值</returns>
        public string GetCookie(string key)
        {
            return httpContextAccessor.HttpContext.Request.Cookies[key];
        }

        /// <summary>
        /// 删除Cookie
        /// </summary>
        /// <param name="key">键</param>
        public void DeleteCookie(string key)
        {
            httpContextAccessor.HttpContext.Response.Cookies.Delete(key);
        }
    }
}

Controller中注入ICookieHelper,代码如下:

using Microsoft.AspNetCore.Mvc;

namespace App.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        private readonly ICookieHelper cookieHelper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cookieHelper"></param>
        public HomeController(ICookieHelper cookieHelper)
        {
            this.cookieHelper = cookieHelper;
        }

        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<string> SetCookie()
        {
            try
            {
                cookieHelper.SetCookie("UserName", "admin", 1);
                cookieHelper.SetCookie("Password", "12345", 1);
                return Ok("添加Cookie成功");
            }
            catch
            {
                return BadRequest("添加Cookie失败");
            }
        }

        /// <summary>
        /// 获取Cookie
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<string> GetCookie()
        {
            try
            {
                return cookieHelper.GetCookie("UserName") + "\n" +
                       cookieHelper.GetCookie("Password");
            }
            catch
            {
                return BadRequest("获取Cookie失败");
            }
        }

        /// <summary>
        /// 删除Cookie
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<string> DeleteCookie()
        {
            try
            {
                cookieHelper.DeleteCookie("UserName");
                cookieHelper.DeleteCookie("Password");
                return Ok("删除Cookie成功");
            }
            catch
            {
                return BadRequest("删除Cookie失败");
            }
        }
    }
}

最后在Startup.cs文件中注册IHttpContextAccessorICookieHelper即可,代码如下所示:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace App
{
    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.AddControllers();
            // 添加IHttpContextAccessor
            services.AddHttpContextAccessor();
            // 添加ICookieHelper
            services.AddSingleton<ICookieHelper, CookieHelper>();
        }

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

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

4、结语

本文主要介绍了ASP.NET CoreCookie的使用方法。如果是在Controller中直接操作Cookie,则可以直接使用HttpContext进行操作。如果需要封装成类,则需要借助IHttpContextAccessor接口进行实现。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值