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
  • 相关阅读:
    python刷新七牛云CDN缓存
    python 操作redis
    redis 设置密码
    redis 允许其他机器连接设置方法
    redis持久化
    redis操作
    redis简介及与memcached比较
    dataframe 处理某列的小数位数并加特殊符号
    django 生成和下载CSV文件
    django 重定向
  • 原文地址:https://www.cnblogs.com/freeliver54/p/6378196.html
Copyright © 2011-2022 走看看