How to use HttpContext.Current in ASP. NET Core

Source: Internet
Author: User
Tags httpcontext

First, preface

As we all know, the ASP. As the latest framework, the MVC5 and ASP. NET WebForm is based on a lot of refactoring. If we want to use the HttpContext.Current in previous versions, it is currently unavailable because the API is not available in ASP.

Of course we can also access the HttpContext in the controller, but in some cases it is not as convenient to use as httpcontext.current.

Second, Ihttpcontextaccessor

With the dependency Injection container system of ASP. NET core, we have the possibility of simulating the API using HttpContext.Current by requesting the Ihttpcontextaccessor interface. However, because the Ihttpcontextaccessor interface is not managed by the instance by dependency injection by default. We will first register it in the servicecollection:

 Public void configureservices (iservicecollection services) {    services. Tryaddsingleton<ihttpcontextaccessor, httpcontextaccessor>();     // Other code ...}

To simulate a httpcontext.current bar:

  Public Static classHttpContext { Public StaticIServiceProvider serviceprovider;  Public StaticMicrosoft.AspNetCore.Http.HttpContext Current {Get            {                ObjectFactory = Serviceprovider.getservice (typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor)); Microsoft.AspNetCore.Http.HttpContext Context=((Microsoft.AspNetCore.Http.HttpContextAccessor) factory).                HttpContext; returncontext; }        }}

 In fact, when it comes to httpcontext.current, we have to mention multithreading, and in previous versions of ASP, it is likely that the httpcontext.current is empty if you encounter a multi-threaded environment. When it comes to this problem there is a solution, that is callcontext;

  CallContext is a dedicated collection object that resembles a thread-local store of method calls and provides a data slot that is unique to each logical execution thread. Data slots are not shared between call contexts on other logical threads. You can add an object to the CallContext when it is propagated round-trip along the execution code path and is checked by individual objects in that path.

While using ASP, the threads in the line castle are reused, but the CallContext is not shared across multiple uses of a thread. Because CallContext is TLS for logical threads, the threads that are reused in the thread pool are kernel objects in the operating system and not managed objects. Just like the unmanaged resource saved in the database connection pool, not the managed resource. Therefore, the two managed threads that have been executed may have reused a physical thread (kernel object) at the bottom, but cannot share the same set of CallContext data slots. Just like the two SqlConnection objects in the new one may use the same physical connection at the bottom, but the properties of the managed object have been reset.

In contrast to ThreadStaticAttribute, the static field of this attribute on the tag is the data stored in the TLS of the physical thread (guessed according to MSDN's description). Not tried), so if two managed thread objects are using the same physical thread internally, this field will be reused (two threads access the same data slot through this field).

In. NET core, there are also new API selection,asynclocal<t>.

third,httpcontextaccessor

Let's take a look at the Ihttpcontextaccessor interface implementation in ASP. NET Core:

  Public classHttpcontextaccessor:ihttpcontextaccessor {#ifNET451Private Static ReadOnly stringLogicaldatakey ="__httpcontext_current__"+AppDomain.CurrentDomain.Id;  PublicHttpContext HttpContext {Get            {                varHandle = Callcontext.logicalgetdata (Logicaldatakey) asObjectHandle; returnHandle?. Unwrap () asHttpContext; }            Set{callcontext.logicalsetdata (Logicaldatakey,NewObjectHandle (value)); }        }#elifNetstandard1_3PrivateAsynclocalNewAsynclocal();  PublicHttpContext HttpContext {Get            {                return_httpcontextcurrent.value; }            Set{_httpcontextcurrent.value=value; }        }#endif}

Finally, I can only say that in the ASP. NET core is everything di ah, in fact, the implementation of the core has long been for us to think of these features, but changed the way to use.

GITHUB:HTTPS://GITHUB.COM/MAXZHANG1985/YOYOFX If you feel you can also invite the Star , Welcome to communicate together.

. NET Core Open Source Learning Group: 214741894

How to use HttpContext.Current in ASP. NET Core

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.