在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

Asp.Net Core3.x中使用Cookie的更多相关文章

  1. .NET Core:在ASP.NET Core WebApi中使用Cookie

    一.Cookie的作用 Cookie通常用来存储有关用户信息的一条数据,可以用来标识登录用户,Cookie存储在客户端的浏览器上.在大多数浏览器中,每个Cookie都存储为一个小文件.Cookie表示 ...

  2. 三分钟学会在ASP.NET Core MVC 中使用Cookie

    一.Cookie是什么? 我的朋友问我cookie是什么,用来干什么的,可是我居然无法清楚明白简短地向其阐述cookie,这不禁让我陷入了沉思:为什么我无法解释清楚,我对学习的方法产生了怀疑!所以我们 ...

  3. 在 ASP.NET Core 应用中使用 Cookie 进行身份认证

    Overview 身份认证是网站最基本的功能,最近因为业务部门的一个需求,需要对一个已经存在很久的小工具网站进行改造,因为在逐步的将一些离散的系统迁移至 .NET Core,所以趁这个机会将这个老的 ...

  4. ASP.NET Core3.0 中的运行时编译

    运行时编译 通过 Razor 文件的运行时编译补充生成时编译. 当 .cshtml 文件的内容发生更改时,ASP.NET Core MVC 将重新编译 Razor 文件 . 通过 Razor 文件的运 ...

  5. Asp.Net中用JS中操作cookie的方法

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="cookies.aspx.cs& ...

  6. 探索Asp net core3中的 项目文件、Program.cs和通用host(译)

    引言 原文地址 在这篇博客中我将探索一些关于Asp.net core 3.0应用的基础功能--.csproj 项目文件和Program源文件.我将会描述他们从asp.net core 2.X在默认模版 ...

  7. 【ASP.NET Web API教程】5.5 ASP.NET Web API中的HTTP Cookie

    原文:[ASP.NET Web API教程]5.5 ASP.NET Web API中的HTTP Cookie 5.5 HTTP Cookies in ASP.NET Web API 5.5 ASP.N ...

  8. 在ASP.NET Core 中使用Cookie中间件

    在ASP.NET Core 中使用Cookie中间件 ASP.NET Core 提供了Cookie中间件来序列化用户主题到一个加密的Cookie中并且在后来的请求中校验这个Cookie,再现用户并且分 ...

  9. Asp.Net MVC 中的 Cookie(译)

    Asp.Net MVC 中的 Cookie(译) Cookie Cookie是请求服务器或访问Web页面时携带的一个小的文本信息. Cookie为Web应用程序中提供了一种存储特定用户信息的方法.Co ...

随机推荐

  1. Docker技术入门与实战第2版-高清文字版

      Docker技术入门与实战第2版-高清文字版 下载地址https://pan.baidu.com/s/1bAoRQQlvBa-PXy5lgIlxUg 扫码下面二维码关注公众号回复100011 获取 ...

  2. WPF桌面程序在请求接口时如何防止被常用的抓包软件Fiddler抓包

    问题:在我开发了一个WPF桌面应用程序的时候,由于涉及到登录等等操作通过Fiddler可以很直观的看到账号密码.首先问题有两点:1.数据提交的时候对于密码等重要的数据没有进行加密操作.2.没有防止抓包 ...

  3. 迷之自信的Single_User Mode

    Alter database Set Single_User 对于任何DBA来说,恐怕都不陌生.在我们需要获取数据库独占访问权来做一些数据库紧急维护的时候,这可能是大多数DBA的首选,但它真的可以实现 ...

  4. Ambiguous mapping. Cannot map 'xxxController' method

    @GetMapping public JsonResp<List<DtoLandRegion>> getLandRegionList() { List<DtoLandRe ...

  5. java循环嵌套与跳转语句(break,continue)

    一 循环嵌套 嵌套循环是指在一个循环语句的循环体中再定义一个循环语句的语法结构.while.do…while. for循环语句都可以进行嵌套,并且它们之间也可以互相嵌套,如最常见的在for循环中嵌套f ...

  6. LeetCode406 queue-reconstruction-by-height详解

    题目详情 假设有打乱顺序的一群人站成一个队列. 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数. 编写一个算法来重建这个队列. 注意: 总人数少于 ...

  7. 基于.NetCore3.1系列 —— 日志记录之自定义日志组件

    一.前言 回顾:日志记录之日志核心要素揭秘 在上一篇中,我们通过学习了解在.net core 中内置的日志记录中的几大核心要素,在日志工厂记录器(ILoggerFactory)中实现将日志记录提供器( ...

  8. Linux学习笔记 一 第一章 Linux 系统简介

    Linux简介 一.UNIX与Linux发展史

  9. Qt开发技术:QCharts(三)QCharts样条曲线图介绍、Demo以及代码详解

    若该文为原创文章,未经允许不得转载原博主博客地址:https://blog.csdn.net/qq21497936原博主博客导航:https://blog.csdn.net/qq21497936/ar ...

  10. Python日期时间(详细)

    获取当前时间戳 import time t = time.time() millis1 = int(t) print('10位时间戳:{}'.format(millis1)) millis2 = in ...