[转]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 ...
随机推荐
- 趣图:快下班了,剩一个bug,修复一下再走
趣图:当我给老板展示我修复了那个 bug 时 趣图:当我以为这是最后一个Bug时……
- 【BZOJ2159】Crash的文明世界 斯特林数+树形dp
Description Crash 小朋友最近迷上了一款游戏--文明5(Civilization V).在这个游戏中,玩家可以建立和发展自己的国家,通过外交和别的国家交流,或是通过战争征服别的国家.现 ...
- iOS 开发之 GCD 不同场景使用
header{font-size:1em;padding-top:1.5em;padding-bottom:1.5em} .markdown-body{overflow:hidden} .markdo ...
- IPython绘图和可视化---matplotlib 入门
最近总是需要用matplotlib绘制一些图,由于是新手,所以总是需要去翻书来找怎么用,即使刚用过的,也总是忘.所以,想写一个入门的教程,一方面帮助我自己熟悉这些函数,另一方面有比我还小白的新手可以借 ...
- sticky footer布局
一.什么是sticky footer 在网页设计中,Sticky footers设计是最古老和最常见的效果之一.它可以概括如下:如果页面内容不够长的时候,页脚块粘贴在视窗底部:如果内容足够长时,页脚块 ...
- 收藏的一些有意思的CSS加载样式
先看下效果 全部代码贴出,自己粘贴调试测试: <!DOCTYPE html> <html lang="en"> <head> <meta ...
- 洛谷 P4001 [ICPC-Beijing 2006]狼抓兔子
题目描述 现在小朋友们最喜欢的"喜羊羊与灰太狼",话说灰太狼抓羊不到,但抓兔子还是比较在行的,而且现在的兔子还比较笨,它们只有两个窝,现在你做为狼王,面对下面这样一个网格的地形: ...
- day--43 HTML标签和CSS基本小结
HTML标签和CSS基本小结一:常用标签 01:块标签 p,h1--h6 ,hr ,div 02:内联标签 b,i,u,s 小提示:块标签可以嵌套内置元素或者某些块级元素,但内联元素不能包含块级元素 ...
- ES6问题记录--Promise
在读[阮一峰]的 ES6 入门文档的时候,有一段代码是这样的. 文章中,还有一段是这样写的 所以,Promise.resolve(3).finally(()=>{}),解析出来的resolve ...
- 洛谷 P2486 [SDOI2011]染色(树链剖分+线段树)
题目链接 题解 比较裸的树链剖分 好像树链剖分的题都很裸 线段树中维护一个区间最左和最右的颜色,和答案 合并判断一下中间一段就可以了 比较考验代码能力 Code #include<bits/st ...