[转]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 ...
随机推荐
- 在ubuntu下安装KDE以及完全卸载KDE
自由转载 ^_^ 同时请注明原文出处:http://www.cnblogs.com/wangvsa/archive/2012/07/22/2603626.html 这是一篇翻译,很多不必要的东西就没翻 ...
- UIView 动画
1.UIView 动画 核心动画 和 UIView 动画 的区别: 核心动画一切都是假象,并不会真实的改变图层的属性值,如果以后做动画的时候,不需要与用户交互,通常用核心动画(转场). UIView ...
- [SinGuLaRiTy] 树链问题
[SinGuLaRiTy-1035] Copyright (c) SinGuLaRiTy 2017. All Rights Reserved. 关于树链 树链是什么?这个乍一看似乎很陌生的词汇表达的其 ...
- 【hadoop】 running beyond virtual memory错误原因及解决办法
问题描述: 在hadoop中运行应用,出现了running beyond virtual memory错误.提示如下: Container [pid=28920,containerID=contain ...
- Trie树【洛谷P3879】 [TJOI2010]阅读理解
P3879 [TJOI2010]阅读理解 题目描述 英语老师留了N篇阅读理解作业,但是每篇英文短文都有很多生词需要查字典,为了节约时间,现在要做个统计,算一算某些生词都在哪几篇短文中出现过. 输入输出 ...
- 190308python-MySQL
一.Python连接MySQL import pymysql conn = pymysql.connect(host='192.168.100.4', port=3306, user='dongfei ...
- Difference **面向过程(或者叫结构化)分析方法**面向对象分析方法
面向过程和面向对象的区别 面向过程是分析出解决问题所需要的步骤,然后一步步实现,面向对象是把构成问事件分解成各个对象,建立对象的目的是为了描述某个事物在整个解决问题的步骤中的行为. 可以说面向对象是从 ...
- (C/C++) Link List - C++ 版本
利用C++寫一個基本的 Link list 練習,功能包含 pint list.CreatList.Insert.Delete.Reverse.Search.Clear.GetLen. 先建立相關的C ...
- JavaWeb学习笔记(一)—— Http协议
一.什么是HTTP协议 HTTP,超文本传输协议(HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议,它是TCP/IP协议的一个应用层协议,用于定义WEB浏览 ...
- vue 遇到的一个问题......
当我用 @tap 或者 @click 触发 ajax事件时,返回的结果会非常慢--- 我也不清楚为啥会这样....(仅仅在chrome下会这样--- 所以 我用 touchend 方法替代了 该方法. ...