In this article we will cover how to Access HttpContext Session and Configuration in helper class in Asp.Net Core 3.1 Application.
Let's Start:
Helper Class
public class DemoClass { private readonly IHttpContextAccessor _httpContext; protected readonly ISession _session; private readonly IConfiguration _configuration; public DemoClass(IHttpContextAccessor httpContextAccessor, IConfiguration configuration) { _httpContext = httpContextAccessor; _session = _httpContext.HttpContext.Session; _configuration = configuration; } public void Get_Data() { string uName = _session.GetString("uName"); string dbConnection = _configuration.GetValue<string>("dbConnection"); } }
Example 1
Register Helper class in "ConfigureServices" method of Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddSession(options => { options.Cookie.HttpOnly = true; }); services.AddHttpContextAccessor(); services.AddControllersWithViews(); //Register Helper Class services.AddSingleton<DemoClass>(); }
public class Example1Controller : Controller { private readonly DemoClass demo; public Example1Controller(DemoClass _demo) { demo = _demo; } public IActionResult Index() { demo.Get_Data(); return View(); } }
Example 2
public class Example2Controller : Controller { private readonly IHttpContextAccessor _httpContext; private readonly IConfiguration _configuration; public Example2Controller(IHttpContextAccessor httpContextAccessor, IConfiguration configuration) { _httpContext = httpContextAccessor; _configuration = configuration; } public IActionResult Index() { DemoClass demo = new DemoClass(_httpContext, _configuration); demo.Get_Data(); return View(); } }
Note:
1) Implement Example 1 if your helper class is used in multiple Controllers.
2) Implement Example 2 if your helper class is used in some Controllers.
Post Comments(0)