Melody
Melody

Reputation: 1203

Session Value is Always null in ASP.NET Core Web API

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

Answers (2)

dush88c
dush88c

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

Nan Yu
Nan Yu

Reputation: 27578

You need provide more details about your codes which doesn't work. But basically you can refer to below steps:

  1. Add ASP.NET Core 2.0 web api application .
  2. Install Microsoft.AspNetCore.Session NuGet package .
  3. Modify your Startup.cs, call AddDistributedMemoryCache and AddSession 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();
    }
    
  4. 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);
    }
    
  5. Then you could make api call to 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

Related Questions