Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
870 views
in Technique[技术] by (71.8m points)

Session variable value is getting null in ASP.NET Core

I am setting a session variable in one method and trying to get the session variable value from the another method in a controller but its always getting null:

Here is my code:

public class HomeController : Controller
{
    public IActionResult Index()
    { 
        HttpContext.Session.SetString("Test", "Hello!");
        var message = HttpContext.Session.GetString("Test");// Here value is getting correctly
        return View();
    }

    public IActionResult About()
    {
        var message = HttpContext.Session.GetString("Test"); // This value is always getting null here

        return View();
    }
}

Here is my session configuration in Startup class:

In ConfigureServices() method:

services.Configure<CookiePolicyOptions>(options =>
{
    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDistributedMemoryCache();
services.AddMvc().AddSessionStateTempDataProvider();
services.AddSession(options =>
{
    options.Cookie.Name = "TanvirArjel.Session";
    options.IdleTimeout = TimeSpan.FromDays(1);
});

In Configure() method:

app.UseSession();
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

Very strange and peculiar problem! Any help will be highly appreciated!

question from:https://stackoverflow.com/questions/49770491/session-variable-value-is-getting-null-in-asp-net-core

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For ASP.NET Core 2.1 and 2.2

In the ConfigureServices method of the Startup class, Set options.CheckConsentNeeded = context => false; as follows:

services.Configure<CookiePolicyOptions>(options =>
{
  // This lambda determines whether user consent for non-essential cookies is needed for a given request.
  options.CheckConsentNeeded = context => false;
  options.MinimumSameSitePolicy = SameSiteMode.None;
});

Problem solved!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...