Detilium
Detilium

Reputation: 3026

Session state in ASP.NET Core

In regular MVC, I'm used to be able to do the following:

public ActionResult SomeAction(){
    Session["User"] = new User();

    return View();
}

Giving me this option in the view:

<div>
    @if(Session["User"] != null){
        <p>Welcome @Session["User"].Username</p>
    }
</div>

In ASP.NET Core, Session state isn't implemented because of the various OS' capable of running this application. I've seen that I can use IMemoryCache and IDistributedCache instead, but I'm not quite sure how, given this scenario.

Any simple and well explained methods for doing this?

Upvotes: 2

Views: 5801

Answers (1)

Detilium
Detilium

Reputation: 3026

Session state in ASP.NET Core is possible. I fixed it by follow these steps:

Add the following package to your project.json:
Microsoft.AspNetCore.Session

Configure the session service

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

        services.AddDistributedMemoryCache();
        services.AddSession(options => 
            // Add any options you want here
            // EXAMPLE
            options.IdleTimeout = TimeSpan.FromSeconds(60);
        );
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseSession();
        app.UseMvcWithDefaultRoute();
    }
}

All done
Now you should be able to do the following in your controller

public class SomeController : Controller
{
    public IActionResult SomeAction()
    {
        TempData["SomeProperty"] = "Some data";
    }
}

And in your view:

<div>
    <p>@TempData["SomeProperty"]</p>
</div>

Further reading material from learn.microsoft.com documentation

Upvotes: 1

Related Questions