aaarianme
aaarianme

Reputation: 292

Unable to set "Session" variable MVC 5

In my controller I pass a model to view

public IActionResult Forgotpassword()
{
    System.Web.HttpContext.Current.Session["sessionString"] = "sample";

    Forgotpasswordinfo Vmodel = new Forgotpasswordinfo();
    return View(Vmodel);
}

I use System.Web.HttpContext.Current.Session["sessionString"] = "sample"; to make a session variable but it shows an error saying HttpContext does not exist!? What am I missing?

Upvotes: 0

Views: 1733

Answers (1)

Victor
Victor

Reputation: 8985

The code below shows how to set up the in-memory session provider:

public class Startup
{    
    //...
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            options.Cookie.Name = ".TestApp.Session";                
            options.IdleTimeout = TimeSpan.FromSeconds(30);
            options.Cookie.IsEssential = true;
        });

        services.AddControllersWithViews();
        services.AddRazorPages();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //...
        app.UseSession();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
            endpoints.MapRazorPages();
        });
    }
}

HttpContext.Session can't be accessed before UseSession has been called.

Setting a variable in the controller:

using Microsoft.AspNetCore.Http;

public IActionResult Index()
{
    HttpContext.Session.SetString("Parameter", "bla bla");
    return View();
}

Obtain the parameter in the view (Index.cshtml):

@using Microsoft.AspNetCore.Http; 
@{    
    string parameter = Context.Session.GetString("Parameter");
}

Mostly the code above is part of example from the Microsoft documentation. For the detailed information see Session and state management in ASP.NET Core.

Upvotes: 1

Related Questions