HttpContext Access in outside of framework another class library services .NET CORE

Issue: We do not have access to HttpContext outside of Controller, Base Controller, and Middleware, But some time we need that in services or another Class library for access Headers or any other thing. So just look at how to achieve it.

  1. Add IHttpContextAccessor in Startup.cs file
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

2. Then simply on which service you would like to call simple call it like.

    public class AnyService
    {
        private readonly IHttpContextAccessor _accessor;

        public HttpContextService(IHttpContextAccessor accessor)
        {
            _accessor = accessor; 
        }

        public HttpContext GetHttpContext()
        { 
            return _accessor.HttpContext;
        }
    }

It comes under using Microsoft.AspNetCore.Http;