在 ASP.NET Core 中 使用 cookies

  cookie 常用于保存用户相关并保存在客户端电脑上的一段数据,在大多数浏览器下,每一个cookie 都会是一个小文件的形式存在,只有 Firefox 例外,它将所有的 cookie 都保存在一个文件中,cookie 是以 key-value 的形式表现的,可以通过这个 key 去 读取,删除,写入 等操作

  ASP.NET Core 中使用 cookie 机制来维护 session 状态,在客户端的每一次请求中,server 端都会将 sessionid 放在 cookie 中发送给客户端来实现用户跟踪

读取Cookie

  • 要想读取 Cookie 可以采用 ASP.NET Core 中的 Request.Cookies 属性,从 Request 对象中读取 cookie
string cookie = Request.Cookies["Key"];
  • 如果你想给 cookie 设置一个过期时间,可以使用 Cookies.Append 重载方法,如下代码所示:
CookieOptions option = new CookieOptions(); 
option.Expires = DateTime.Now.AddMilliseconds(10); 
Response.Cookies.Append(key, value, option); 

  从上面代码中可以看到,在生成 Cookie 的过程中可以使用 CookieOptions 来给其配置一些额外参数

参数 说明
Domain 用于指定 cookie 关联的域级别
Expiration time 用于指定 cookie 的过期时间
Path 用于指定 cookie 的路径
Security policy 用于指定 cookie 是否可以通过 Https 访问
HttpOnly 用于指定 cookie 是否是在 server 端可用

写入 cookie

  • 要想写 cookie,可以利用 Cookies.Append 方法
Response.Cookies.Append(somekey, somevalue);

删除 cookie

  • 要想删除 cookie,可以利用 Cookies.Delete 方法
Response.Cookies.Delete(somekey);

使用 HttpContext

  如何在 ASP.NET Core 中使用 cookie,要想得到 cookie 必须要有 Request 对象,要想得到 Request 对象 必须要有 HttpContext,要想得到 HttpContext 必须要利用 IHttpContextAccessor 接口

 public interface IHttpContextAccessor
{
    
    
	HttpContext HttpContext {
    
     get; set; }
}
  • ASP.NET Core 中就内置了一个实现了该接口的 HttpContextAccessor
public class HttpContextAccessor : IHttpContextAccessor
{
    
    
	public HttpContextAccessor();

	public HttpContext HttpContext {
    
     get; set; }
}

  有些朋友可能要问,为啥这里不直接使用父类 ControllerRequestHttpContext,这是因为此方式是一种强依赖,接下来给大家演示如何通过依赖注入的方式获取 HttpContext,此种更加灵活。

  为了实现依赖注入,需要将 IHttpContextAccessorHttpContextAccessor 注入到 ServiceCollection 中,下面就用单例的模式进行注入

public void ConfigureServices(IServiceCollection services)
{
    
    
	services.AddSingleton<IHttpContextAccessor,
	HttpContextAccessor>();
	// 逻辑代码
}

  然后就可以通过依赖注入的方式获取 IHttpContextAccessor 接口的实例,再依次获取 HttpContext 对象,下面的代码片段展示了如何在 Controller 中访问 IHttpContextAccessor 实例

public class HomeController : Controller
{
    
    
    private readonly IHttpContextAccessor _httpContextAccessor;
    public HomeController(IHttpContextAccessor httpContextAccessor)
    {
    
    
        this._httpContextAccessor = httpContextAccessor;
    }   
  // 逻辑代码
}

在 Controller 中写入 cookie

  • 在 Controller 中通过如下方法将 数据 写入 cookie
public IActionResult Write(string key, string value, bool isPersistent)
{
    
    
	CookieOptions options = new CookieOptions();
	if (isPersistent)
		options.Expires = DateTime.Now.AddDays(1);
	else
		options.Expires = DateTime.Now.AddSeconds(10);
	_httpContextAccessor.HttpContext.Response.Cookies.Append(key, value, options);
	return View("WriteCookie");
}

在 Controller 中读取 cookie

  • 一旦 cookie 成功写入之后,就可以用如下方法读取 cookie
public IActionResult Read(string key)
{
    
    
	ViewBag.Data = _httpContextAccessor.HttpContext.Request.Cookies[key];
	return View("ReadCookie");
}
  • 可以使用 浏览器的 开发者工具 来查看 Cookie 是否成功写入并读取到

====

猜你喜欢

转载自blog.csdn.net/qq_43562262/article/details/112094968