did you inject a HttpContextAccessor into the controller? if so, use debugger to check if null when passed to the controller's constructor. if null, then you have startup configuration issues.
Error when checking if HttpContextAccessor.HttpContext.Session.GetString(key_name) has value or not

Hi there
I'm using VS 2019 community, in my application that using .net core MVC I'm trying to check if user signed in or not by checking the value of Session - HttpContextAccessor.HttpContext.Session.GetString(key_name) -, it is okay if user signed in, but if not he try to open a View it must redirect to home control, in my case when use try to open (https://localhost:12345/User) exception occur {System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
}
here is my code in startup.cs file
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddHttpContextAccessor();
// Step 1 to use session
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(15);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCookiePolicy();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
//pattern: "{controller=Doc}/{action=Index}/{id?}"
);
});
}
and there is my code when trying to check if session has value to continue viewing index, or navigate to another view:
var d = HttpContextAccessor.HttpContext.Session.GetString(key_UN);
if (d == null)
{
RedirectToAction("index", "Home");
}
So if there ais any advice I will appreciate that
thanks
2 additional answers
Sort by: Most helpful
-
AdamJachocki 6 Reputation points
2021-09-07T14:24:09.61+00:00 It looks like Session is empty. I mean there is no session at this point. Try:
var d = HttpContextAccessor.HttpContext.Session?.GetString(key_UN);
Notice the question mark.
-
Islam Youssef 21 Reputation points
2021-09-07T16:08:20.423+00:00 Hi there (AGAIN)
after searching and a little of luck I think I've got the solution!, it is not logic but it worked.
I wrote startup.cs again with a different order of methods
this my code
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();// Step 1 to use session //services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(15); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; //options.Cookie.Name = ".islam.cookie"; }); services.AddMemoryCache(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); // Step 2 to use seeion --> watch out the order app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}" //pattern: "{controller=Doc}/{action=Index}/{id?}" ); }); }
and this was the result when I check if session has a value or not
SO thanks Adam and Bruse, I appreciate your quick help, and if there are any source to study asp.net core mvc from I will be thank full