Cannot access session asp.net core

Viewed 16644

Hi please help me im trying to test sessions in asp.net core but when i set the session and get it from other controller it appears to be null

heres my startup

public class Startup
{

    public IConfigurationRoot Configuration { get; }
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }


    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc().AddJsonOptions(options => {
            options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        });

        // Adds a default in-memory implementation of IDistributedCache.
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(600);
            options.CookieHttpOnly = true;
        });


        services.AddSingleton<IConfiguration>(Configuration);
        services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
        services.AddTransient<IApiHelper, ApiHelper>();



    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseSession();
        app.UseDeveloperExceptionPage();
        if (env.IsDevelopment())
        {
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
                HotModuleReplacement = true,
                ReactHotModuleReplacement = true
            });
        }

        //var connectionString = Configuration.GetSection("ConnectionStrings").GetSection("ClientConnection").Value;


        app.UseStaticFiles();
        loggerFactory.AddConsole();


        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });
    }

    public static void Main(string[] args) {
        var host = new WebHostBuilder()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseKestrel()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

and here is how i set the session

public class HomeController : Controller
{
    public IActionResult Index()
    {

        HttpContext.Session.SetString("Test", "Ben Rules!");

        return View();
    }

    public IActionResult Error()
    {
        return View();
    }
}

and here my sample code of getting the session again but it appears to be null

    [HttpGet("[action]")]
    public IEnumerable<JobDescription> GetJobDefinitions()
    {
        //this is always null
        var xd = HttpContext.Session.GetString("Test");


        var x = _apiHelper.SendRequest<Boolean>($"api/JobRequest/GetJobRequest",null);
        var returnValue = new List<JobDescription>();
        returnValue = jobDescriptionManager.GetJobDescriptions();
        return returnValue;


    }

Thanks for the help

2 Answers

To use Session in your MVC App, you have to: Install Microsoft.AspNetCore.Session NuGet package.

In Startup.cs ConfigureServices add the AddSession():

services.AddMvc();
services.AddSession(options => {
         options.IdleTimeout = TimeSpan.FromHours(1);
});

In Startup.cs configure add the UseSession():

app.UseSession();
app.UseMvc();

And now you can use it in the controller:

Set the Session

string token="xx";    
HttpContext.Session.SetString("UserToken", token);

Get the stored value

var token = HttpContext.Session.GetString("UserToken");

Additionally, ASP.NET Core 2.1+ introduced some additional extension points like a cookie consent dialog. So we require consent to store cookies from the user.

If you click "Accept" on the privacy banner, then ASP.NET Core is able to write the session cookie.

Related