问题
I need to do something on Session End Event. How can I access this event? anything similar to this event maybe timeout?
回答1:
The only way to handle this in ASP.NET Core
- on page load on client side (in JS
code) to schedule the timer for session timeout and warn the user when it's close to expire. If user responds - ping server side (to refresh the session), or redirect th euser to logout page is not. Your session timeout can be configured in Startup
class. So you need to pass the same value to client view, setup a timer (let say it is 20 minutes) to show the modal after 19 minutes to the user with counting down timer for a minute and a button like "Stay Online". When the user clicks the button - do AJAX
call to server side (some Ping
action in your Home
controller, or something like that).
回答2:
ASP.NET has a Session_OnEnd
event you could register in Global.asax, but even then it was highly unreliable: you could only use it with in-proc sessions and it could only monitor the session expiration, not when a user does something like close the browser window.
ASP.NET Core has nothing similar, though, mostly because it really doesn't make sense to. More than anything, ASP.NET Core is designed for scale, something in-proc anything is the antithesis of. Session store is distributed by default. Even when you do use in-memory sessions, it's still using an implementation of IDistributedCache
. Having a distributed session store makes monitoring expirations untenable, so such functionality has not been added.
More to the point, sessions are not actively expired. Instead, it's when the user next sends back the session cookie, after allowing the session to expire, that the session is destroyed and a new session created. Also sessions employ sliding expirations, so as long as the user remains active within the timeout window, the session will effectively never expire.
Long and short, what you're looking for is not possible. However, this does sort of scream XY problem. You've got some sort of problem you need to solve (X), and you've decided the way to solve it is to do something on session expiration (Y). However, you can't figure out how to do Y, either, so you're asking a question about Y, when you should really be asking about X. I would suggest creating a new question about the actual problem you need to solve; there's likely a better way.
来源:https://stackoverflow.com/questions/53190635/capture-session-timeout-on-server-side-in-asp-net-core-2-1