zoukankan      html  css  js  c++  java
  • [转]ASP.NET Core / MVC 6 HttpContext.Current

    本文转自: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
  • 相关阅读:
    C++Primer 中间Sales_items.h头文件
    2014最不受欢迎10编程语言种
    解决ubuntu 14.04删ibus导致系统设置项目的损失后,,退出关机问题是不正常的
    会计翻译成英文
    Delphi 使用 Format格式话字符串的用法
    浅谈暂估应付账款的会计处理
    Delphi TcxTreelist 设置scrollbars 不起作用的原因
    Delphi 调试 通过BreakPoint
    折现率”的公式
    考会计证 需要的科目
  • 原文地址:https://www.cnblogs.com/freeliver54/p/6378196.html
Copyright © 2011-2022 走看看