[转]ASP.NET Core / MVC 6 HttpContext.Current

本文介绍在 ASP.NET Core 中如何通过依赖注入和服务配置两种方式来获取当前的 HttpContext 对象。依赖注入的方式是将 HttpContext 注入到服务中直接使用;另一种方式则是创建一个静态类 HttpHelper 来保存 HttpContext 的引用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文转自:http://www.spaprogrammer.com/2015/07/mvc-6-httpcontextcurrent.html

As you know with MVC 6, HttpContext is rewritten and one of the most used functionality , HttpContext.Current is dropped. In most situations you don’t need this and you should use Controller context. But in some situations you may need access to HttpContext. In my scenario I want to pass some data using HttpContext.Items from one layer (middleware) to another (business layer).
 
Below are the two ways to get current HttpContext:
 
 
  • Using dependency injection we can inject the HttpContext on to the service directly. DI injects a singleton object called HttpContextAccessor which is used to retrieve the current HttpContext. Here is the sample code for this

 

    public class MyService
    {
        private HttpContext context;
        public MySerivce(IHttpContextAccessor contextAccessor)
        {
            this.context = contextAccessor.HttpContext;
        }
 
 
  •  Similar to HttpContext.Current we can also create a static class that holds the reference for the current HttpContext. Here is the code for this static class

 

    public static class HttpHelper
    {
        private static IHttpContextAccessor HttpContextAccessor;
        public static void Configure(IHttpContextAccessor httpContextAccessor)
        {
            HttpContextAccessor = httpContextAccessor;
        }
 
        public static HttpContext HttpContext
        {
            get
            {
                return HttpContextAccessor.HttpContext;
            }
        }
    }
 
This static HttpHelper class stores the singleton HttpContextAccessor and is then used to return the current HttpContext. We will configure our HttpHelper in our startup as shown below
 
        public void Configure(IApplicationBuilder app)
        {
            //other code             
    HttpHelper.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
        }
 
Finally we can get current HttpContext wherever we need using our Helper as below
HttpHelper.HttpContext
 
As you see using the above two approaches to get the current HttpContext.
Please see my updated post on this. I am using CallContext to pass the HttpContext and other data ASP.NET Core Async Context Data
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值