F Andrei
F Andrei

Reputation: 708

How to use Sessions in ASP vNext

How can I use session variables in ASP MVC 6 ?

I couldn't find a working sample on how to store and use session variables . Can anyone help ?

Upvotes: 6

Views: 2720

Answers (2)

Bart Calixto
Bart Calixto

Reputation: 19705

add package "Microsoft.AspNet.Session": "1.0.0-beta8" to project.json and then using Microsoft.AspNet.Http;

inside that namespace you have extension methods for context.

you also need to use it with DI on Startup.cs :

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSession();
    }

Here's a sample controller :

using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;

namespace MvcWebApp.Controllers
{
    [Route("[controller]")]
    public class SomeController : Controller
    {
        public async Task<IActionResult> Edit()
        {
            HttpContext.Session.SetInt("myVar", 35);
        }
    }
}

Upvotes: 4

agua from mars
agua from mars

Reputation: 17424

there is a sample on the session repo on github: https://github.com/aspnet/Session/tree/release

And you can access to the session by the Controler's Session property

Upvotes: 1

Related Questions