Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session variable in view

Some time ago I created some simply login with session. It was a MVC app but with .net framework 4.6 if I'm correct. And I could there use something like

<h2>@Session["ID"]</h2>

And ID from session variable should be in h2 tag. But now I try to build same but with .net core 2.0.

My startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddDbContext<L2Context>(options =>
            options.UseSqlite("Data Source=test.db"));

    services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(30);
    });
}

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

    app.UseStaticFiles();
    app.UseSession();

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

Controller to save data into session:

[HttpPost]
public IActionResult Login(Users user)
{
    var optionsBuilder = new DbContextOptionsBuilder<L2Context>();
    optionsBuilder.UseSqlite("Data Source=test.db");

    using (L2Context db = new L2Context(optionsBuilder.Options))
    {
        var user = db.Users.Single(u => u.Login == user.Login && u.Password == user.Password);
        if (user != null)
        {
            HttpContext.Session.SetString("ID", user.ID.ToString());
            HttpContext.Session.SetString("Login", user.Login.ToString());
            return RedirectToAction(nameof(LoggedIn));
        }
        else
        {
            ModelState.AddModelError("", "Login or password is invalid");
        }
    }
    return View();
}

LoggedIn View:

@{
    ViewData["Title"] = "LoggedIn";
}

<h4> Hello @Session["Login"]</h4>

So, do I have some error here? I tough it was working last time when I used it.

I get:

error CS0103: The name 'Session' does not exist in the current context

like image 938
Thou Avatar asked Oct 17 '25 18:10

Thou


1 Answers

In ASP.NET Core, the View doesn't have access to the Session property of the HttpContext object by default. You can access it by importing the Http Namespace within the view:

//import the namespace to make the class available within the view
@using Microsoft.AspNetCore.Http

You can then access the Session property of the HttpContext object:

<h4> Hello @HttpContext.Session.GetString("Login")</h4>
like image 132
Camilo Terevinto Avatar answered Oct 20 '25 08:10

Camilo Terevinto