Asp.Net Core获取当前上下文对象

HttpContext简介

.Net Core中的HttpContext上下文是个抽象类,命名空间为Microsoft.AspNetCore.Http

所在程序集

\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll

 定义代码:

namespace Microsoft.AspNetCore.Http
{
    //
    // 摘要:
    //     Encapsulates all HTTP-specific information about an individual HTTP request.
    public abstract class HttpContext
    {
        protected HttpContext();

一、在Mvc 控制器实例中包含了上下文对象

        public IActionResult Index()
        {
            HttpContext _context = this.HttpContext;
            return View();
        }

二、定义静态的IServiceProvider,全局获取当前请求上下文

特别说明此方法新版本中放弃使用,请使用其他方式:https://www.cnblogs.com/tianma3798/p/10361644.html

1.定义类

    public class TestOne
    {
        public static IServiceProvider ServiceProvider;
        public static HttpContext GetContext()
        {
            object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));

            HttpContext context = ((IHttpContextAccessor)factory).HttpContext;

            return context;
        }
    }

2.在配置文件Startup中,获取

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider svp)
        {
            TestOne.ServiceProvider = svp;
.....
        }

3.再其他任何地方使用

        public IActionResult Index()
        {
            HttpContext _context = this.HttpContext;
            if (_context == TestOne.GetContext())
                return Content("上线文相同");
            return View();
        }

注意:

因为IHttpContextAccessor接口默认不是由依赖注入进行实例管理的。

我们先要将它注册到ServiceCollection中,不然在IIS发布后获取factory实例为null

public void ConfigureServices(IServiceCollection services)
{
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Other code...
}

 

更多:

Asp.Net Core 视图整理(一)

Asp.Net Core异常处理整理

.Net Core配置文件读取整理

posted @ 2017-08-18 19:12  天马3798  阅读(3458)  评论(0编辑  收藏  举报