本文转自:http://stackoverflow.com/questions/37329354/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的更多相关文章

  1. ASP.NET Core 运行原理解剖[4]:进入HttpContext的世界

    HttpContext是ASP.NET中的核心对象,每一个请求都会创建一个对应的HttpContext对象,我们的应用程序便是通过HttpContext对象来获取请求信息,最终生成响应,写回到Http ...

  2. [C#].Net Core 获取 HttpContext.Current 以及 AsyncLocal 与 ThreadLocal

    在 DotNetCore 当中不再像 MVC5 那样可以通过 HttpContext.Current 来获取到当前请求的上下文. 不过微软提供了一个 IHttpContextAccessor 来让我们 ...

  3. .NET Core 获取 HttpContext.Current 以及 AsyncLocal 与 ThreadLocal

    在 DotNetCore 当中不再像 MVC5 那样可以通过 HttpContext.Current 来获取到当前请求的上下文. 不过微软提供了一个 IHttpContextAccessor 来让我们 ...

  4. 在.NET Core中使用Jwt对API进行认证

    在.NET Core中想用给API进行安全认证,最简单的无非就是Jwt,悠然记得一年前写的Jwt Demo,现在拿回来改成.NET Core的,但是在编码上的改变并不大,因为Jwt已经足够强大了.在项 ...

  5. 备忘】HttpContextAccessor类

    AspNetCore / src / Http / Http / src / HttpContextAccessor.cs // Copyright (c) .NET Foundation. All ...

  6. 浅析 .NET 中 AsyncLocal 的实现原理

    目录 前言 1.线程本地存储 2.AsyncLocal 实现 2.1.主体 AsyncLocal<T> 2.2.AsyncLocal<T> 在 ExecutionContext ...

  7. ASP.NET Core管道详解[2]: HttpContext本质论

    ASP.NET Core请求处理管道由一个服务器和一组有序排列的中间件构成,所有中间件针对请求的处理都在通过HttpContext对象表示的上下文中进行.由于应用程序总是利用服务器来完成对请求的接收和 ...

  8. Cookie和Session的那些事儿

    Cookie和Session都是为了保持用户的访问状态,一方面为了方便业务实现,另一方面为了简化服务端的程序设计,提高访问性能.Cookie是客户端(也就是浏览器端)的技术,设置了Cookie之后,每 ...

  9. 【.NET】Cookie操作类

    public static class CookiesHelper { /// <summary> /// Cookies赋值 /// </summary> /// <p ...

随机推荐

  1. c++类 初始化另一对象

    Cbox类中对象a  可以直接赋值给对象b,无论类中数据成员是私有还是共有.且在创建a时调用了一次构造函数,b调用的是另外的默认构造函数: #include<iostream> using ...

  2. windows下安装newman

    1.下载安装node.js,下载地址::https://nodejs.org/en/download/,这里我下载的为v10.15.0-x64.msi,下载后直接安装即可,安装完后可输入node -v ...

  3. React进阶篇(1) -- react-router4模块化

    本篇内容: 单一的路由无嵌套 多层嵌套路由 获取路径中的参数 按需加载 单一的路由无嵌套 routers.js import Home from 'components/Home'; import N ...

  4. EF进阶篇(一)——概述

    前言 以前在ITOO里面和图书馆项目开发的时候,采用的这个技术,但是总是对上下文那里不是特别清楚.上下文这个概念很是模糊,所以这次再次拿起这个技术点儿,然后复习了一遍,发现我以前想的好简单. 内容 E ...

  5. loj2289 [THUWC 2017]在美妙的数学王国中畅游(LCT+Taylor展开)

    link 题目大意: 你需要维护一个树 每个点都有个sin(ax+b)或exp(ax+b)或ax+b 你需要维护一些操作:连边.删边.修改某个点的初等函数.询问某条树链上所有函数带入某个值后权值和或不 ...

  6. 分享记录一批免费VIP视频解析接口,不定时更新!

    VIP视频接口的作用相信大家都懂,那么,由于接口的维护.开发具有不稳定性,失效率很高.这里收集一些目前可用的接口,如果不能用,请反馈给我删除,感谢大家! 电影<西虹市首富>优酷链接:htt ...

  7. 主机和虚拟机互Ping的问题

    主机能ping通虚拟机,虚拟机能ping不通主机. 发现原来是被防火墙阻止了.打开主机防火墙禁止Ping的方式. 在ping不通的电脑上对防火墙进行如下设置:依次单击“防火墙”—“高级设置”—“入站规 ...

  8. 数据库分库分表配置sharding-jdbc

    @Bean(name = "shardingDataSource", destroyMethod = "close") @Qualifier("sha ...

  9. 【转】idea project中导入其他文件夹下的模块,可能出现java.io.FileNotFoundException: XXX.xml

    在一个project 中导入一个java 模块, 我要执行该模块的main函数 ,在main函数中有一个 FileReader(“generatorConfig.xml”) 而generatorCon ...

  10. 校园网络安全CTF 第一题 和 你真了解我吗?

    第一题: 需要先找到相应头(REsponse header中的tips) <?php$flag = "***";if (isset($_GET['repo']))//检测变量 ...