Reputation: 1203
I am trying to store the values in session in asp.net core web api project. I have referred the below link to store the values in session. https://andrewlock.net/an-introduction-to-session-storage-in-asp-net-core/
But i am getting null always while getting session value.
Upvotes: 4
Views: 5262
Reputation: 2106
Following tutorial will help to set up Session values in server-side in ASP .Net Core Web API application.
Tutorial for Session in API Core
Upvotes: 0
Reputation: 27578
You need provide more details about your codes which doesn't work. But basically you can refer to below steps:
Modify your Startup.cs, call AddDistributedMemoryCache
and AddSessio
n methods in ConfigureServices function , and add UseSession
method in Configure function :
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDistributedMemoryCache();
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSession();
app.UseMvc();
}
Get/Set session in controller(using Microsoft.AspNetCore.Http;) :
[HttpGet("setSession/{name}")]
public IActionResult setsession(string name)
{
HttpContext.Session.SetString("Name", name);
return Ok("session data set");
}
[HttpGet("getSession")]
public IActionResult getsessiondata()
{
var sessionData = HttpContext.Session.GetString("Name");
return Ok(sessionData);
}
http://localhost:xxxxx/api/ControllerName/setSession/derek
to set session , and call to http://localhost:xxxxx/api/ControllerName/getSession
to get session data .Upvotes: 1