How to Create and Access Session .net core api?

15,215

Solution 1

Actually .net core can access session easily. Session mechanism is a basic feature in aspnet (.netcore as well) https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2

I think you just need to add

    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        // Set a short timeout for easy testing.
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
    });

in ConfigureServices and:

app.UseSession();

in Configure

Then you can use it anywhere by injecting ISession where you need. As this is distributed by design you should serialize your data using something like JsonConvert.SerializeObject and deserialize them back.

This feature described here has nothing with security concepts.

Solution 2

In Startup.cs you can add cookie authentication by adding this line (you can also specify options for length of session, etc).

services.AddAuthentication().AddCookie();

To create a session on sign-in, from a controller, you can call this to sign in as a user with a set of claims (basically key/value pairs that describe what you need to know about the user):

await HttpContext.SignInAsync(userId, claims);

This creates a ClaimsPrincipal that can be accessed via the User property on Controller:

User.HasClaim("someclaim", "somevalue")

Ultimately the middleware encrypts the claims and saves them to a cookie, so the authentication is still stateless from the server's perspective. Be aware though that the encryption key it uses by default is tied to the machine so you'll have to use something like azure or redis if you plan on scaling to multiple server instances.

If you want to have a full login & user management system, the easiest way to go is probably ASP.net identity which provides the APIs for handling users, policies, access groups, and some of the tricky stuff like password storage using Entity Framework. For more info on that, check out this: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.2&tabs=visual-studio


As a side-note, for more generic session state, this document has data about other session state options, but since you asked about logins, the best option is probably to use the authentication APIs.

Solution 3

All right, there are two things you need to do. In startup.cs:

1- Add app.UseSession(); to Configure method.

2- For more controlling on cookies insert following codes into ConfigureServices method:

options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;

Like this if it solved problem.

Share:
15,215
SATHEESH  P
Author by

SATHEESH P

Updated on June 19, 2022

Comments

  • SATHEESH  P
    SATHEESH P almost 2 years

    I need to create and access session in api. For example i have api called Login,Profile. When the login api is called at that time i need to create session and i need to access the session in profile api. When the session is cleared the login and profile api don't allow the user to access. How to do it.

    Thank you..

  • Venugopal M
    Venugopal M almost 3 years
    The question pertains to Web API Controllers and NOT MVC Controllers.
  • Asif Ali
    Asif Ali over 2 years
    does this also work for an API base project
  • Sribin
    Sribin almost 2 years
    Injecting ISession ? Can you please elaborate