(this might not work how I want, WIP)
From : https://www.c-sharpcorner.com/article/configure-sql-server-session-state-in-asp-net-core/
Project.json
"tools": {
"Microsoft.Extensions.Caching.SqlConfig.Tools": "1.0.0-preview2-final"
}
Use the following command
dotnet sql-cache create "Data Source=.\SQLExpress;Initial Catalog=Test;Integrated Security=True;" "dbo" "SQLSessions"
SQL session state internally uses memory cache, so as to enable SQL Server session. We need to add "Microsoft.Extensions.Caching.SqlServer" dependency along with "Microsoft.AspNet.Session" into project.json file.
project.json
{
"version": "1.0.0-*",
"buildOptions": {
"preserveCompilationContext": true,
"debugType": "portable",
"emitEntryPoint": true
},
"tools": {
"Microsoft.Extensions.Caching.SqlConfig.Tools": "1.0.0-preview2-final"
},
"dependencies": {},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
},
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.0",
"Microsoft.AspNetCore.Session" : "1.0.0",
"Microsoft.Extensions.Caching.SqlServer" : "1.0.0",
"Microsoft.Extensions.Configuration.Json" : "1.0.0"
},
"imports": "dnxcore50"
}
}
}
Startup.cs
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace WebApplication {
public class Startup{
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = @"Data Source=.\SQLExpress;Initial Catalog=Test;Integrated Security=True;";
options.SchemaName = "dbo";
options.TableName = "SQLSessions";
});
services.AddSession(options => {
options.CookieName = "Test.Session";
options.IdleTimeout = TimeSpan.FromMinutes(60);
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app){
app.UseSession();
app.UseMvc();
app.Run(context => {
return context.Response.WriteAsync("Hello Readers!");
});
}
}
}
Implementation
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
public class HomeController : Controller
{
[Route("home/index")]
public IActionResult Index()
{
HttpContext.Session.SetString("name","Jignesh Trivedi");
return View();
}
[Route("home/GetSessionData")]
public IActionResult GetSessionData()
{
ViewBag.data = HttpContext.Session.GetString("name");
return View();
}
}