[转]How to use IHttpContextAccessor in static class to set cookies
While i would advise staying away from static class scenarios like this, it is still possible to achieve what you are asking for.
In the Startup.ConfigureServices
method you can call services.BuildServiceProvider()
to get the IServiceProvider
to resolve the type you seek. It's a bit of a hack but it works.
Assuming a static class like...
public class MyStaticHelperClass {
private static IHttpContextAccessor httpContextAccessor;
public static void SetHttpContextAccessor(IHttpContextAccessor accessor) {
httpContextAccessor = accessor;
}
public static void addReplaceCookie(string cookieName, string cookieValue) {
var HttpContext = httpContextAccessor.HttpContext;
if (HttpContext.Request.Cookies(cookieName) == null) {
// add cookie
HttpCookie s = new HttpCookie(cookieName);
s.Value = cookieValue;
s.Expires = DateTime.Now.AddDays(7);
HttpContext.Response.Cookies.Add(s);
} else {
// ensure cookie value is correct
HttpCookie existingSchoolCookie = HttpContext.Request.Cookies(cookieName);
existingSchoolCookie.Expires = DateTime.Now.AddDays(7);
existingSchoolCookie.Value = cookieValue;
HttpContext.Response.Cookies.Set(existingSchoolCookie);
}
}
}
You would configure your class during start up
public IServiceProvider ConfigureServices(IServiceCollection service) {
services.AddTransient<IMyService, MyService>();
services.AddMvc();
//this would have been done by the framework any way after this method call;
//in this case you call the BuildServiceProvider manually to be able to use it
var serviceProvider = services.BuildServiceProvider();
//here is where you set you accessor
var accessor = serviceProvider.GetService<IHttpContextAccessor>()
MyStaticHelperClass.SetHttpContextAccessor(accessor);
return serviceProvider;
}
Now with that done. I would still strongly advise converting your static class into a service whose concrete implementation would use the IHttpContextAccessor
as a dependency that can be injected via its constructor.
public interface ICookieService {
void AddReplaceCookie(string cookieName, string cookieValue);
}
public class CookieService : ICookieService {
IHttpContextAccessor httpContextAccessor;
public CookieService(IHttpContextAccessor httpContextAccessor) {
this.httpContextAccessor = httpContextAccessor;
}
public void AddReplaceCookie(string cookieName, string cookieValue) {
var HttpContext = httpContextAccessor.HttpContext;
if (HttpContext.Request.Cookies(cookieName) == null) {
// add cookie
HttpCookie s = new HttpCookie(cookieName);
s.Value = cookieValue;
s.Expires = DateTime.Now.AddDays(7);
HttpContext.Response.Cookies.Add(s);
} else {
// ensure cookie value is correct
HttpCookie existingSchoolCookie = HttpContext.Request.Cookies(cookieName);
existingSchoolCookie.Expires = DateTime.Now.AddDays(7);
existingSchoolCookie.Value = cookieValue;
HttpContext.Response.Cookies.Set(existingSchoolCookie);
}
}
}
...that could then be registered with the Services collection...
public void ConfigureServices(IServiceCollection service) {
services.AddTransient<ICookieService, CookieService>();
services.AddMvc();
}
...and be available for injection into classes that have need of it's use.
public class SomeClassThatNeedCookieServicesController : Controller {
ICookieService cookieService;
public SomeClassThatNeedCookieServicesController(ICookieService cookieService) {
this.cookieService = cookieService;
}
}
This is how I do it to manage session cookies in my applications.
[转]How to use IHttpContextAccessor in static class to set cookies的更多相关文章
- ASP.NET Core 运行原理解剖[4]:进入HttpContext的世界
HttpContext是ASP.NET中的核心对象,每一个请求都会创建一个对应的HttpContext对象,我们的应用程序便是通过HttpContext对象来获取请求信息,最终生成响应,写回到Http ...
- [C#].Net Core 获取 HttpContext.Current 以及 AsyncLocal 与 ThreadLocal
在 DotNetCore 当中不再像 MVC5 那样可以通过 HttpContext.Current 来获取到当前请求的上下文. 不过微软提供了一个 IHttpContextAccessor 来让我们 ...
- .NET Core 获取 HttpContext.Current 以及 AsyncLocal 与 ThreadLocal
在 DotNetCore 当中不再像 MVC5 那样可以通过 HttpContext.Current 来获取到当前请求的上下文. 不过微软提供了一个 IHttpContextAccessor 来让我们 ...
- 在.NET Core中使用Jwt对API进行认证
在.NET Core中想用给API进行安全认证,最简单的无非就是Jwt,悠然记得一年前写的Jwt Demo,现在拿回来改成.NET Core的,但是在编码上的改变并不大,因为Jwt已经足够强大了.在项 ...
- 备忘】HttpContextAccessor类
AspNetCore / src / Http / Http / src / HttpContextAccessor.cs // Copyright (c) .NET Foundation. All ...
- 浅析 .NET 中 AsyncLocal 的实现原理
目录 前言 1.线程本地存储 2.AsyncLocal 实现 2.1.主体 AsyncLocal<T> 2.2.AsyncLocal<T> 在 ExecutionContext ...
- ASP.NET Core管道详解[2]: HttpContext本质论
ASP.NET Core请求处理管道由一个服务器和一组有序排列的中间件构成,所有中间件针对请求的处理都在通过HttpContext对象表示的上下文中进行.由于应用程序总是利用服务器来完成对请求的接收和 ...
- Cookie和Session的那些事儿
Cookie和Session都是为了保持用户的访问状态,一方面为了方便业务实现,另一方面为了简化服务端的程序设计,提高访问性能.Cookie是客户端(也就是浏览器端)的技术,设置了Cookie之后,每 ...
- 【.NET】Cookie操作类
public static class CookiesHelper { /// <summary> /// Cookies赋值 /// </summary> /// <p ...
随机推荐
- 第十二篇 os模块
Python的os模块提供了系统相关,目录,文件操作,执行命令等操作. 1.文件和目录操作相关的方法: 方法 说明 os.mkdir 创建目录 os.rmdir 删除目录 os.rename 重命名 ...
- #论文笔记# [pix2pixHD] High-Resolution Image Synthesis and Semantic Manipulation with Conditional GANs
Ting-Chun Wang, Ming-Yu Liu, Jun-Yan Zhu, Andrew Tao, Jan Kautz, and Bryan Catanzaro. "High-Res ...
- spring 学习(一):使用 intellijIDEA 创建 maven 工程进行 Spring ioc 测试
spring学习(一):使用 intellijIDEA 创建 maven 工程进行 Spring ioc 测试 ioc 概念 控制反转(Inversion of Control,缩写为IOC),是面向 ...
- 题解 P1534 【不高兴的津津(升级版)】
题目链接 不算太难.就是题目有歧义. wa了好几次才发现.上一天要是小于8的话.结算是昨天一个负值在加上今天课时数.再减去8.233.... 而不是上一天小于8个小时.就清零了..大家要注意(ps:题 ...
- springcloud微服务 总结一
一 什么是微服务 译文: 微服务架构是一种架构模式,它提倡将单一应用程序划分成一组小的服务,服务之间互相协调.互相配合,为用户提供最终价值.每个服务运行在其独立的进程中,服务与服务间采用轻量级的通信机 ...
- python中的set实现不重复的原理
最近在尝试写选课系统的时候遇到一个问题: 1.存在两个类 School.Teacher : 2.School实例中包含多个Teacher的实例,但又不可重复 本人想到在School中用set()存储, ...
- python安装环境配置、python模块添加、sublime text编辑器配置
前提: 本文讲述的是 windows环境 python相应的安装配置. 进入官网找安装包,官网地址如下:https://www.python.org/downloads/ 找到相应2.7.x或3.x ...
- HDU6395(分段+矩阵快速幂)
题目:http://acm.hdu.edu.cn/showproblem.php?pid=6395 给你一个式子,给出你A,B,C,D,P,n,让你求出第n项的式子Fn.(其中ABCDPn均在1e9的 ...
- vim的多窗口功能与环境参数设置
Vim的多窗口功能 多窗口情况下按键功能 :sp [filename] 打开一个新的窗口,如果有加filename,表示在新窗口打开一个新文件,否则表示两个窗口为同一文件内容 :[ctrl]+w+j( ...
- Jquery 循环内间隔执行 异步执行
<script type="text/javascript"> var arr = new Array(); var arrk = 0; jQuery(function ...