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
的相关操作封装成类又该怎么办呢?在上面的代码中,我们主要是用HttpContext
对Cookie
进行操作,但HttpContext
是ControllerBase
的一个属性,我们定义的操作类难道要继承它吗?
在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
文件中注册IHttpContextAccessor
和ICookieHelper
即可,代码如下所示:
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 Core
中Cookie
的使用方法。如果是在Controller
中直接操作Cookie
,则可以直接使用HttpContext
进行操作。如果需要封装成类,则需要借助IHttpContextAccessor
接口进行实现。