Ehsan Ghanbari

Experience, DotNet, Solutions

HttpContext in asp.net core

Accessing to HttpContext in asp.net core application is just like before, for example:

 

 public class MyController : Controller

    {

        [HttpGet]

        public ActionResult Show()

        {

            var user = HttpContext.User;

            return View();

        }

    }

 

 But HttpContext is not available everywhere in your solution! For IHttpContextAccessor. If you are using the default dependency injection of Ap.net Core then you should example to access to HttpContext in layers rather than web, you should inject a new interface of asp.net core named firstly resolve the mentioned interface in it:

 

public void ConfigureServices(IServiceCollection services)

        {

            services.Configure<CookiePolicyOptions>(options =>

            {

                // This lambda determines whether user consent for non-essential cookies is needed for a given request.

                options.CheckConsentNeeded = context => true;

                options.MinimumSameSitePolicy = SameSiteMode.None;

            });

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        }

 

Now you can inject the interface wherever you are going to use HttpContext:

 

   public interface ISampleService

    {

    }

 

    public class SampleService : ISampleService

    {

        private readonly IHttpContextAccessor _httpContextAccessor;

 

        public SampleService(IHttpContextAccessor httpContextAccessor)

        {

            _httpContextAccessor = httpContextAccessor;

        }

    }

 

To tell the truth, I don't like this kind of using HttpContext in the outside scope of the controller. It's an antipattern in my point of view because HttpContext and every related thing to the web should live in the web project. By the way! Using HttpContext in Razor view engine is just like before!

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I'm spending a lot of my time on software architecture. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
comments powered by Disqus