gavv
gavv

Reputation: 4883

How does HttpContext property work in ASP.NET Core?

I'm aware that HttpContext property of controller is async-safe. When you call it inside async action, it always returns context of the current action.

But I'm curious how is this achieved?

If I understand correctly, it can't be implemented using thread-local storage technique. Because after await, an async method can resume on another thread from pool. Or, on the other hand, while an async method is "sleeping", the same thread from pool can execute another async method.

Upvotes: 0

Views: 487

Answers (2)

gavv
gavv

Reputation: 4883

As suggested by @Damien_The_Unbeliever, HttpContext property indeed uses AsyncLocal, as described in this article:

namespace Microsoft.AspNetCore.Http
{
    public class HttpContextAccessor : IHttpContextAccessor
    {
        private static AsyncLocal<HttpContext> _httpContextCurrent = new AsyncLocal<HttpContext>();

        public HttpContext HttpContext
        {
            get
            {
                return _httpContextCurrent.Value;
            }
            set
            {
                _httpContextCurrent.Value = value;
            }
        }
    }
}

Upvotes: 0

Paulo Morgado
Paulo Morgado

Reputation: 14836

From HttpContext access from a background thread:

HttpContext access from a background thread

HttpContext isn't thread-safe. Reading or writing properties of the HttpContext outside of processing a request can result in a NullReferenceException.

Storing the HttpContext instance and passing it along or using IHttpContextAccessor interface can get you in trouble because of that.

A controller should collect the necessary request information to pass along to other components/services and use the result of that invocation to contribute response.

Upvotes: 1

Related Questions