user3720465
user3720465

Reputation: 35

Razor Session Data - HttpContextAccessor is null

I am a MVC5 newbie, creating a test web Site to look at MVC5 and Razor

I have a very simple site after user logs on and I need to change menus via _Layout from "Login" to add "Logout" "Account".

Note: The site is has its own authentication, I will look at single login later.

I am really struggling with managing session data in MVC5, not sure which is the best approach. I have tried TEMP DATA , but although I peak I have found that after user has been redirected between a couple of pages the data is lost. So looked at good old cookie, but since GDPR I can tell there is a lot less default support for cookies out of the box.

Anyway in the Startup I believe I am doing all the right things

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                                   options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });   
            services.AddDistributedMemoryCache();  
            services.AddSession(options =>
            {
                // Set session timeout value
                options.IdleTimeout = TimeSpan.FromSeconds(30);
                options.Cookie.HttpOnly = true;
            });
        }


services.AddMvc();
services.AddCaching(); 
services.AddSession();
services.AddHttpContextAccessor();

dependency inject it in , but in the Post when I attempt to call the SetString , the "private readonly IHttpContextAccessor _httpContextAccessor;" is null

Oddly the _Layout is not throwing same null exception

   @using Microsoft.AspNetCore.Http
   @inject IHttpContextAccessor HttpContextAccessor

   @{
        string UserId = HttpContextAccessor.HttpContext.Session.GetString("UserId");
   }

After working on ASP.Net , the simple approach to handling Session , beginning to question whether I have missed something as it seems a lot of work in MVC5. So should I be using a different approach in MVC5

Upvotes: 0

Views: 4695

Answers (2)

Sanjay Kumar
Sanjay Kumar

Reputation: 345

Set

options.CheckConsentNeeded = context => false;

this to true i.e

options.CheckConsentNeeded = context => true;

and your session will not be null anymore.

Upvotes: 0

user3720465
user3720465

Reputation: 35

Just want to add this this for anyone else , probably not the cleanest code With help form Sanjay now got a crude site up and running

Startup class , example code

public class Startup {

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {

        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddHttpContextAccessor();
        services.AddRazorPages();

        services.AddRazorPages();
        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromSeconds(30);
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseSession();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}

}

Code for .csHtml

@using Microsoft.AspNetCore.Http;
@inject IHttpContextAccessor HttpContextAccessor

@{
    if (Context.Session.GetString("UserRole") != null)
    {

code for .cs

    private readonly IHttpContextAccessor HttpContextAccessor;
    public LoginModel(ISiteUserService siteUserService, 
        IHttpContextAccessor httpContextAccessor)
    {
        this.HttpContextAccessor = httpContextAccessor;        
    }
    public IActionResult OnGet()
    {

        if(HttpContextAccessor.HttpContext.Session.GetString("UserRole")!= null)
        {

Upvotes: 1

Related Questions