本文转自: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. 接上一篇,Springcloud使用feignclient远程调用服务404 ,为什么去掉context-path后,就能够调通

    一.问题回顾 如果application.properties文件中配置了 #项目路径 server.servlet.context-path=/pear-cache-service 则feigncl ...

  2. request payload

    最近在调试代码时发现有Request Payload的情况,从网上查一些文件,也都有较多的描述.下面我只是说明一下大家没有注意的地方 关于HTTP请求,都是通过URL及参数向后台发送数据.主要方式有G ...

  3. 2. C语言文件操作经典习题

    1. 统计英文文本文件中,有多少个大写字母.小写字母.数字.空格.换行以及其他字符. #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> ...

  4. django日期查询出现UTC日志转换CONVERT_TZ出错的问题

    select CONVERT_TZ(NOW(), 'UTC', 'UTC') 出现NULL值, 原因是MySQL少了时区表: SELECT * FROM mysql.time_zone; SELECT ...

  5. RUCM简介

    一.动机 UCM:用例建模,主要用于结构化和文档需求方面. UCSs:用例规格说明书,通常是文本文档,所以描述中不可避免含有歧义. RUCM:限制性用例建模.目标 G1.使UCMs更加可理解并且更精确 ...

  6. [SDOi2012]Longge的问题 BZOJ2705 数学

    题目背景 SDOi2012 题目描述 Longge的数学成绩非常好,并且他非常乐于挑战高难度的数学问题.现在问题来了:给定一个整数N,你需要求出∑gcd(i, N)(1<=i <=N). ...

  7. Linux磁盘占满 no space left on device

    假如当前文件删除了,如果还有其他进程还在使用这个文件,这个文件删不干净:https://www.cnblogs.com/heyonggang/p/3644736.html 在Linux下查看磁盘空间使 ...

  8. Qt 学习之路 2(35):文件

    Qt 学习之路 2(35):文件 豆子 2013年1月5日 Qt 学习之路 2 12条评论 文件操作是应用程序必不可少的部分.Qt 作为一个通用开发库,提供了跨平台的文件操作能力.从本章开始,我们来了 ...

  9. git 各个区的区别

    Git有三大区(工作区.暂存区.版本库)以及几个状态(untracked.unstaged.uncommited) 把文件往Git版本库里添加的时候,是分两步执行的: 第一步是用 git add 把文 ...

  10. windows使用putty工具 进行【复制】,【粘贴】操作

    #复制# 按住鼠标左键,执行选择,放开左键时完成复制 #粘贴# 点击鼠标右键,执行粘贴