Scenario:
Create a Sign on service to allow creation of users in our app. Add user details to session
Solution:
- Add NuGet
Microsoft.AspNet.Core.Session
- In Startup.cs under Configure method
//add before UseEndpoints or if using Mvc as before UseMvc
app.UseSession();
- In Startup.cs under ConfigureServices method
1
2
| services.AddDistributedMemoryCache();
services.AddSession(options => { options.Cookie.Name = ".solutionName.Session"; options.IdleTimeout = TimeSpan.FromMinutes(5); });
|
- Set session as below
1
2
3
4
5
6
7
8
9
10
11
| try
{
var userList = string.Join(",", result.Item2.ToArray());
HttpContext.Session.SetString("users", userList + " in Home controller");
ViewBag.success = true;
ViewBag.Name = userList;
}
catch (Exception e)
{
throw;
}
|
- Read session data as below
1
2
| var users = HttpContext.Session.GetString("users");
ViewBag.Name = users;
|
|
|
No comments:
Post a Comment