1

In my Web api when a user login successfully I set session with some values like

  HttpContext.Session.SetObject("CurrentUserID", user.Id);
                HttpContext.Session.SetObject("CurrentUserRoles",user.Roles);

and just return token and some values to save in cookie

  return Ok(new
                {
                    Id = user.Id,
                    Username = user.UserName,
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Token = tokenString,
                    role = user.Roles
                });

But when the client hit api action which has this line

  List<string> userRolesList = HttpContext.Session.GetObject<List<string>>("CurrentUserRoles");

Then always get null value even I have added session inside Startup >Configure

like

 app.UseSession();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });

and ConfigureService also

 services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds( 60 * 60);
            options.Cookie.HttpOnly = true;
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

but does work still... Please help.

TAHA SULTAN TEMURI
  • 4,031
  • 2
  • 40
  • 66

1 Answers1

1

HTTP is a stateless protocol. Sessions are fake state, enabled by both a server-side and client-side component. The client-side component is a cookie: specifically a Set-Cookie response header. In order for the session to be restored on the next request, the value of this Set-Cookie response header must be sent back via the Cookie request header with each request. A web browser (the client) will do all this automatically, including persisting the cookie locally. However, a thin client like HttpClient, Postman, etc. will not. You would need to independently persist the cookie from the response header and then attach it to each request via the Cookie header in order to maintain the session between requests.

That said, this is a major reason why APIs typically do not, and honestly should not make use of sessions. It's simply a pattern that doesn't make much sense in an API context, and only adds a potential point of failure, since clients must pay attention to the cookie headers, and take manual actions to handle the cookies.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444