0

I have been trying to pass the ISession from my ControllerBase to an underlying library.

I have a Class library, where I'd like to use the Session.

While the ControllerBase uses Microsoft.AspNetCore.Http, then when using the Session in my class, as ISession, then it wants to install a nuget package Microsoft.AspNetCore.Http.Features. This however this is another ISession, which e.g. lacks Get/SetString, I can only use Set/Get which works on byte arrays. How do I get this right?

Another thing, I have 2 controllers - will they have the same session?

To me it looks like session data are lost when I use the other controller. Once I make a call to the other and back to the first, then my session data seem lost.

sonnich
  • 151
  • 2
  • 11

1 Answers1

0

The solution is as follows

Use the Nuget package Microsoft.AspNetCore.Http.Extensions It should be offered when using the static class SessionExtensions

In code when calling the Class Library, e.g.

public class MyClassLibrary: IDisposable
{
    public MyClassLibrary(ISession session)
    {
        var stored = SessionExtensions.GetString(session, "MyStorageName");
        if (stored == null)
            SessionExtensions.SetString(session, "MyStorageName", "Hello world");

Then it is only left to pass the HttpContext.Session from the Controller

As an additional hint, storing table data/arrays/lists, it can be done using JsonSerializer.Deserialize<List<MyRowClass>>(stored) and JsonSerializer.Serialize()

sonnich
  • 151
  • 2
  • 11