Home > Net >  Session management in Angular and ASP.NET
Session management in Angular and ASP.NET

Time:10-11

So I'm trying to learn how to use sessions to store info about a logged in users. I'm using .net core for my backend and Angular for my front end and I have 2 main questions

1> So when I create a session variable using HttpContext.Session.SetString("key", "value"); will it automatically store the session id in the browser or is it something I need to do manually? And how do I make sure that the session id is coming in with the request ?

2> How do I access the session id from a middleware to use it to get that particular user's information? Like for example if there are certain pages only an admin can access and the session needs to show that the user is an admin how would I go about implementing that in the middleware?

I tried searching on google but all it came up with is JWT, but I would like to use sessions over it. Sorry for the noob questions. Any help is appreciated.

CodePudding user response:

by using following code you can set session and local storage in angular

localStorage.set("id",2);
sessionStorage.set("id",2);

by using following code you can Getsession and local storage in angular

localStorage.get("id")
sessionStorage.get("id");```

CodePudding user response:

When using the code HttpContext.Session.SetString("key", "value"); session will be created and associated with the browser you don't need any other action.

You can access the session via HttpContext - which will be injected in the startup class and accessed via the constructor like this public async Task InvokeAsync(HttpContext context)

And in the startup class, you can add the following code services.AddHttpContextAccessor() which will help you to inject HTTP context to middlewares.

  • Related