Blog

Filter posts by Category Or Tag of the Blog section!

HttpContext in asp.net core

Thursday, 18 October 2018

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!

Category: Software

Tags: Asp.Net

comments powered by Disqus