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配置文件讀取整理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM