Getting session data without passing from Service

Historically with one of our apps we’ve really only used Session for Auth purposes and there is almost no logic that cares about the user - other than group membership everyone is treated the same. Therefore, we don’t pass context around.

However, that’s changing now…

So this is probably a dumb question… but is there any easier way to have a function deep in a call stack get session data without passing it all the way down from the service method?

What we normally do is attach the object we want to the Session, and then use it in any service call.

as an example:

###1. create your object

    public class MyCustomAuthSession: AuthUserSession
        public MyCustomAuthSession() { }

        public B2BCustomer B2BCustomer {get; set;}
            public long OrderId {get; set;}

###2. register the object:

           new AuthFeature(() => 
                new MyCustomAuthSession(), 
                new IAuthProvider[] {  ...  })));

###3. populate it upon authentication

      public override bool TryAuthenticate (
             IServiceBase authService, string userName, string password)
         var customer = new B2BCustomer();

          // authenticate as normal
          // then if authenticated, get the object an attach to the session 

          var session = authService.GetSession(false) as MyCustomAuthSession;
          session.B2BCustomer = customer;

###4. retrieve the session on your service

       public object Put(OrderItems request)
           var session = this.GetSession() as GkoAuthSession;

Is this what you are looking for, or I just didn’t understood the question? :frowning:

1 Like

Ok, yes, I have all that working.

Maybe better stated my question is… can a method outside the service object gain session context without it being passed explicitly down.

I think the answer to my question is no. We have a lot of retrofitting to do.

If you’re using an ASP.NET Host you can get the Session from the IRequest with:

var req = HostContext.TryGetCurrentRequest();
var session = req.GetSession();

But this doesn’t work in HttpListener Self-Hosts so we recommend against it.

If you’re able to pass the Users SessionId (e.g. ss-id Cookie) you can also retrieve the Session from the ICacheClient directly, e.g:

var sessionKey = SessionFeature.GetSessionKey(sessionId);
var session = HostContext.Cache.Get<AuthUserSession>(sessionKey);