I'm attempting to use session variables in my Razor Pages application. I installed the NuGet package "Microsoft.AspNetCore.Session". Here is my Startup.cs file:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();
services.AddSession();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseSession();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
}
This is my function:
public string GetText()
{
if (HttpContext.Session.GetString("_MessageText") != null)
{
return HttpContext.Session.GetString("_MessageText");
}
else
{
return "You found an easter egg.";
}
}
And I call it like this:
<div class="col align-self-center">
@Message.GetText()
</div>
The error I get for Session.GetString() is:
NullReferenceException: Object reference not set to an instance of an object.
I assume it has to do with HttpContext, but I thought that was instantiated with app.UseSession(). Anyone have any suggestions?