在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. win10下visual studio code安装及mingw C/C++编译器配置,launch.json和task.json文件的配置

    快一年了,我竟然还有脸回来..... 过去一年,由于毕设.找工作的原因,发生太多变故,所以一直没更(最主要的原因还是毅力不够...),至于发生了什么事,以后想说的时候再更吧..依然是小白,下面说正事. ...

  2. 笨办法学python3练习代码11-12:print()

    ex11.py print("How old are you? ",end = " ") #加入end = " ",则函数不再自动换行 ag ...

  3. 2017面向对象程序设计(Java)第十七周助教工作总结

            本学期已接近尾声,java课程也即将结束.经过一学期的java学习,相信大家已经从最初的懵懂.困惑渐渐的走向了柳暗花明,并对java的体系结构有了更加清晰的认识.但一学期的学习是远远不 ...

  4. 双下划线开头的attr方法

    # class Foo: # x=1 # def __init__(self,y): # self.y=y # # def __getattr__(self, item): # print('执行__ ...

  5. 038_go语言中的状态协程

    代码演示: package main import ( "fmt" "math/rand" "sync/atomic" "time ...

  6. XCTF-WEB-高手进阶区-Web_python_template_injection-笔记

    Web_python_template_injection o(╥﹏╥)o从这里开始题目就变得有点诡谲了 网上搜索相关教程的确是一知半解,大概参考了如下和最后的WP: http://shaobaoba ...

  7. C++游戏(大型PC端枪战游戏)服务器架构

    实习期间深入参与到某大型pc端枪战游戏的后端开发中,此游戏由著名游戏工作室编写,代码可读性极高,自由时间对游戏后台代码进行了深入研究,在满足自身工作需要的同时对游戏后台的架构也有了理解,记录在此,以便 ...

  8. Collections.synchronizedMap()与ConcurrentHashMap区别

    Collections.synchronizedMap()与ConcurrentHashMap主要区别是:Collections.synchronizedMap()和Hashtable一样,实现上在调 ...

  9. java容器源码分析及常见面试题笔记

      概览 容器主要包括 Collection 和 Map 两种,Collection 存储着对象的集合,而 Map 存储着键值对(两个对象)的映射表. List Arraylist: Object数组 ...

  10. Mysql Lost connection to MySQL server at ‘reading initial communication packet', system error: 0

    在用Navicat for MySQL远程连接mysql的时候,出现了 Lost connection to MySQL server at ‘reading initial communicatio ...