Session - Set/Get session in service


Scenario:

Create a Sign on service to allow creation of users in our app. Add data added details to session

Solution:

  1. Add NuGet Microsoft.AspNet.Core.Session
  2. In Startup.cs under Configure method

  3. //add before UseEndpoints or if using Mvc as before UseMvc
    app.UseSession();

  4. In Startup.cs under ConfigureServices method

  5. 1
    2
    services.AddDistributedMemoryCache();
    services.AddSession(options => { options.Cookie.Name = ".solutionName.Session"; options.IdleTimeout = TimeSpan.FromMinutes(5); });
    

  6. Set IHttpContextAccessor

  7. 1
    2
    3
    4
    5
    6
    7
    private readonly IHttpContextAccessor _httpContextAccessor;
    
    public SignOnService(ILogger<SignOnService> logger, IHttpContextAccessor httpContextAccessor)
    {
     _logger = logger;
     _httpContextAccessor = httpContextAccessor;
    }

  8. Set session data as below

  9.  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

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...