Scenario:
Create a Sign on service to allow creation of users in our app. Add data added 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 IHttpContextAccessor
1
2
3
4
5
6
7
| private readonly IHttpContextAccessor _httpContextAccessor;
public SignOnService(ILogger<SignOnService> logger, IHttpContextAccessor httpContextAccessor)
{
_logger = logger;
_httpContextAccessor = httpContextAccessor;
}
|
| |
- Set session data as below
1
2
3
4
5
6
7
8
9
10
11
12
13
| //return back to client one user at a time
foreach (var user in users)
{
try
{
_httpContextAccessor.HttpContext.Session.SetString("message", "Processed request at : " + DateTime.Now.ToString());
await responseStream.WriteAsync(user);
}
catch (Exception e)
{
throw;
}
}
|
No comments:
Post a Comment