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 _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的更多相关文章
- .NET Core:在ASP.NET Core WebApi中使用Cookie
一.Cookie的作用 Cookie通常用来存储有关用户信息的一条数据,可以用来标识登录用户,Cookie存储在客户端的浏览器上.在大多数浏览器中,每个Cookie都存储为一个小文件.Cookie表示 ...
- 三分钟学会在ASP.NET Core MVC 中使用Cookie
一.Cookie是什么? 我的朋友问我cookie是什么,用来干什么的,可是我居然无法清楚明白简短地向其阐述cookie,这不禁让我陷入了沉思:为什么我无法解释清楚,我对学习的方法产生了怀疑!所以我们 ...
- 在 ASP.NET Core 应用中使用 Cookie 进行身份认证
Overview 身份认证是网站最基本的功能,最近因为业务部门的一个需求,需要对一个已经存在很久的小工具网站进行改造,因为在逐步的将一些离散的系统迁移至 .NET Core,所以趁这个机会将这个老的 ...
- ASP.NET Core3.0 中的运行时编译
运行时编译 通过 Razor 文件的运行时编译补充生成时编译. 当 .cshtml 文件的内容发生更改时,ASP.NET Core MVC 将重新编译 Razor 文件 . 通过 Razor 文件的运 ...
- Asp.Net中用JS中操作cookie的方法
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="cookies.aspx.cs& ...
- 探索Asp net core3中的 项目文件、Program.cs和通用host(译)
引言 原文地址 在这篇博客中我将探索一些关于Asp.net core 3.0应用的基础功能--.csproj 项目文件和Program源文件.我将会描述他们从asp.net core 2.X在默认模版 ...
- 【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 ...
- 在ASP.NET Core 中使用Cookie中间件
在ASP.NET Core 中使用Cookie中间件 ASP.NET Core 提供了Cookie中间件来序列化用户主题到一个加密的Cookie中并且在后来的请求中校验这个Cookie,再现用户并且分 ...
- Asp.Net MVC 中的 Cookie(译)
Asp.Net MVC 中的 Cookie(译) Cookie Cookie是请求服务器或访问Web页面时携带的一个小的文本信息. Cookie为Web应用程序中提供了一种存储特定用户信息的方法.Co ...
随机推荐
- Linux的VMWare中Centos7文件权限管理chown 和 chmod
文件管理 chown chmod 1./根目录下目录功能划分 /boot/ 存放系统启动程序菜单及核心 --可以单独使用文件系统 /etc/ 存放系统中所有配置文件 /bin/ ...
- hdu6787(骰子+往回推的传输带问通过方案,dp)
题:http://acm.hdu.edu.cn/showproblem.php?pid=6787 题意:有1~n标号的格子,上面有m个传输带(传送带传的位置要传到之前去,1位置不能有格子)1~11的骰 ...
- Xposed原理分析
目录 安卓系统启动 什么zygote? 安卓应用运行? Xposed介绍 Xposed构成 Xposed初始化大体工作流程 源码分析 初始化 app_main#main app_main#initia ...
- 【HNOI2009】最小圈 题解(SPFA判负环+二分答案)
前言:模拟赛考试题,不会做,写了个爆搜滚蛋仍然保龄. --------------------- 题目链接 题目大意:给定一张有向图,求一个环,使得这个环的长度与这个环的大小(所含结点个数)的比值最小 ...
- SmartDb代码修改
在之前的一篇博客中介绍过SmartDB(https://blog.csdn.net/wuquan_1230/article/details/89145012),在使用的过程中发现一个问题,会造成内存泄 ...
- Python 面向对象之高级编程
7.面向对象高级编程 7.1使用__slots__ python动态语言,new 对象后绑定属性和方法 Tip:给一个实例绑定的方法,对其他对象无效.可以通过对class绑定后,所有对象可以调用该方法 ...
- leetcode刷题笔记-1. 两数之和(java实现)
题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,数组中同一个元素不能使 ...
- C# 8.0 的新特性概览和讲解
本文转自 https://blog.csdn.net/hez2010/article/details/84036742 C# 8.0 的新特性概览和讲解 前言 新的改变 可空引用类型(Nullable ...
- C#LeetCode刷题之#121-买卖股票的最佳时机(Best Time to Buy and Sell Stock)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4014 访问. 给定一个数组,它的第 i 个元素是一支给定股票第 ...
- docker基础入门理解
本文简单的介绍了一下docker的一些优点,以及使用方法 1. 理解docker 1.1 docker是什么? 1.2 为什么要使用Docker? 2. docker安装 3. docker-容器,镜 ...