Coder Social home page Coder Social logo

Session Events about session HOT 21 CLOSED

aspnet avatar aspnet commented on May 23, 2024
Session Events

from session.

Comments (21)

John0King avatar John0King commented on May 23, 2024 7

@Tratcher please implement sessionOnStart sessionOnEnd events, It's a good way to trace how many user visited your site in 30 minutes

from session.

Tratcher avatar Tratcher commented on May 23, 2024 4

A) updating LastActivity shouldn't be a bottleneck if you set a minimum update window (e.g. only update if it's been at least five minutes since the last update). This is similar to how we do sliding refresh on login cookies.
B) As for the job, it again depends on how often you want it to run and/or how granular you need it to be. E.g. The default session idle timeout is 20min, so your job spacing could easily be that high and it would be unlikely to cause perf issues.

from session.

Imemygithub avatar Imemygithub commented on May 23, 2024 2

@Tratcher What if I want to send a mail notification when the session ends? (Yes, we are using InProc). Is there any other way to track the session ends?

from session.

Tratcher avatar Tratcher commented on May 23, 2024 2

A session 'ends' when the client loses the cookie (e.g. closes the browser), or is inactive long enough for the cached data to be cleared from the server. The first situation is impossible to detect. The second is impractical as distributed caches have no cleanup notification mechanisms, and you can't even assume it's strictly time based as the entries may also be removed due to memory pressure. Local caches could have an expiration notification, but again we don't want to add features to session that can only work in a local environment.

I think the closest you can manage is having a LastActivity timestamp in your user database and a job that periodically executes a given task for users that have reached a specified idle threshold. This would also let you send additional follow up reminders like "we noticed you haven't come back for a few days...", and would work across devices.

from session.

Tratcher avatar Tratcher commented on May 23, 2024 1

You appear to be conflating browser sessions with login sessions. There is no direct relation between the two, they are distinct mechanisms an application may use to track the user.

I read through this description of the old events again. I can see where someone might have used onStart, but that work is better accomplished in middleware now. Consider:

app.Use(async (context, next) =>
{
  int visits = context.Session.GetInt32("IKnowYou") ?? 0;
  if (visits == 0 && CheckIfThisRequestNeedsToUseSession(context))
  {
     // New session, do any initial setup and then mark the session as ready
     context.Session.SetInt32("IKnowYou", 1);
     // ...
  }
  await next();
});

I don't think OnEnd makes sense in ASP.NET 5. The docs for the old one said it fired when sessions expired, but only for InProc sessions. The new Session design focuses on making sure everything works in distributed scenarios, we wouldn't add something that only worked locally. Having an event trigger when Abandon/Cancel/Clear is called also doesn't make sense to me. You can either just call your cleanup code directly, or check the validity of your data in the session via middleware at the end of the request (similar to the above example, but check after await next()).

from session.

hishamco avatar hishamco commented on May 23, 2024 1

@Tratcher thanks for your clarification, nothing but checking the validity of the data session after await next() is a headache specially if you have some data stored in the session, perhaps some pages change some of them those data, so providing such events will let the web devs focusing on their business logic rather than writing a tedious code that may fails in some unexpected situations

from session.

ErcinDedeoglu avatar ErcinDedeoglu commented on May 23, 2024 1

@Tratcher @davidfowl @muratg
If you are not going to implement session onend; why we're setting the sessiontimeout?
I read all of above, but not implementing sesion onend is really strange decision. Every application uses session events. Also @Tratcher adviced that we can store data on sql not session. This is also not acceptable...

My issue is I need session start event to recognize user from its cookie to auto login. But I cant handle session start atm...

from session.

ErcinDedeoglu avatar ErcinDedeoglu commented on May 23, 2024 1

Still have same probem, session start OK but I can't get session end. How I can solve it?

My solution for session start:

            app.Use((httpContext, nextMiddleware) =>
            {
                string sessionID = httpContext.Session.Get<string>("SessionID");

                if (!string.IsNullOrEmpty(sessionID))
                {
                    //Session Start
                    httpContext.Session.Set("SessionID", UniqueHelper.ShortId.Generate(true, false, 32));
                }

                return nextMiddleware();
            });

Session end?

from session.

Tratcher avatar Tratcher commented on May 23, 2024

Not at present. What would you do with them?

from session.

hishamco avatar hishamco commented on May 23, 2024

@Tratcher those hooks will allow the web devs to do whatever they want. For example onSessionEnd we may show a login popup, change user login status or persist a shopping cart in a database and much more

from session.

Imemygithub avatar Imemygithub commented on May 23, 2024

@Tratcher thanks for your clarification, I don't know how far this job functionality is feasible but definitely there will be a performance bottle neck if introduce something like this which periodically check the user activity. Please let me know your thought on this.

from session.

Imemygithub avatar Imemygithub commented on May 23, 2024

That make sense. Thanks for your time.

from session.

shafqatalix avatar shafqatalix commented on May 23, 2024

I have upgraded my project to asp.net core now the only issue is Session_OnEnd(), in our business logic we need to do bunch of activities on session timeout, i am stuck in finding any solution in asp.net core? is there any plans to implement some sort of SessionEnd() or we need to stick to older aspe.net?

from session.

Tratcher avatar Tratcher commented on May 23, 2024

We don't currently have any plans for an OnEnd event. See my comments above #20 (comment)

What kind of business logic would you run in OnEnd?

from session.

shafqatalix avatar shafqatalix commented on May 23, 2024

Thanks Tratcher, I need to populate some database tables, some counters and at last send email every-time when session timeout & logout. The logout is very straightforward but timeout is tricky. The SQL job is not going to work in our case because we don't have anything like "LastActivity timestamp" etc; plus if we need to modify database schema thats more than million dollar investment because more than 50 we applications reads the single database and all those needs to be tested with any database schema change. Is there any workaround to do SessionEnd() kind of thing?

from session.

Tratcher avatar Tratcher commented on May 23, 2024

You need to detect expirations in the data store (IDistributedCache, e.g. Redis or SQL). Which store are you using? We should take that discussion over to https://github.com/aspnet/caching

from session.

cwishva avatar cwishva commented on May 23, 2024

@Tratcher

I need to do a Audit when the session ends, so that we can track what the user operations in his Session.

Do you think this can be implemented in another way ?

from session.

hishamco avatar hishamco commented on May 23, 2024

You can audit after checking whether the session is expired or not, this could be goes after await next()

from session.

Tratcher avatar Tratcher commented on May 23, 2024

@chanaka1 No, only the cache knows the session has expired. The most the middleware knows is if it receive a cookie with no matching entry in the cache then it can assume expiration.

from session.

muratg avatar muratg commented on May 23, 2024

Hi, it looks like you are posting on a closed issue/PR/commit!

We're very likely to lose track of your bug/feedback/question unless you:

  1. Open a new issue
  2. Explain very clearly what you need help with
  3. If you think you have found a bug, include detailed repro steps so that we can investigate the problem

from session.

hovek avatar hovek commented on May 23, 2024

You appear to be conflating browser sessions with login sessions. There is no direct relation between the two, they are distinct mechanisms an application may use to track the user.

I read through this description of the old events again. I can see where someone might have used onStart, but that work is better accomplished in middleware now. Consider:

app.Use(async (context, next) =>
{
  int visits = context.Session.GetInt32("IKnowYou") ?? 0;
  if (visits == 0 && CheckIfThisRequestNeedsToUseSession(context))
  {
     // New session, do any initial setup and then mark the session as ready
     context.Session.SetInt32("IKnowYou", 1);
     // ...
  }
  await next();
});

I don't think OnEnd makes sense in ASP.NET 5. The docs for the old one said it fired when sessions expired, but only for InProc sessions. The new Session design focuses on making sure everything works in distributed scenarios, we wouldn't add something that only worked locally. Having an event trigger when Abandon/Cancel/Clear is called also doesn't make sense to me. You can either just call your cleanup code directly, or check the validity of your data in the session via middleware at the end of the request (similar to the above example, but check after await next()).

Consider a situation where you have multiple steps that user can take and every next step depends on a previous one taken where he has chosen something and that has been stored in the session (a lot of in-memory objects) so that when he re-visits the same link he can automatically continue where he left off. There is too many info to be stored in cookies or URL, it bests fits into the session based cache and I want that cache to be cleared when the session expires without having to write extra code to check periodically if the session is no longer and then dispose of the cache and free-up the memory. An alternative to not having session objects and having to track previous interactions in a web app is to redesign the web app so that all the session cache is stored locally in the client's browser/PC and that client is the one to tell the server exactly what he needs, but that is a major change/redesign and it throws much of the logic to JavaScript and away from the server and also client wouldn't be able to continue where he left off when page is refreshed.

from session.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.