Reputation: 26645
I have tried things from this SO question. But it didn't help me. All answers seem not working. I don't want to check whether Session is null or not and redirect to other page in every method. I tried to redirect in Session_end event, but it is not working because it does not have an HTTP context associated with it.
So, what is the best practice?
Thanks.
Upvotes: 0
Views: 377
Reputation: 113292
Best practice is not to redirect in a case like this.
Let's say you are a user on a website, and you want to go to http://example.net/theInterestingBit
.
Now let's imagine your session has expired.
Was what you wanted that you would go to /theInterestingBit
if your session was alive, but otherwise you would go to /someLoginPage
"successfully"? Probably not.
What you wanted was to go to /theInterestingBit
and not care about "sessions" because that's something for programmers to worry about not you. That you failed to do so isn't a success condition, it's an error condition.
So don't redirect, instead use HttpServerUtility.Transfer
or HttpContext.RewritePath
so that the user still goes to /theInterestingBit
but that becomes a login page or other appropriate means to start a new session. Make sure the response uses a status-code of 403 so it's appropriately noted as an error page, rather than a "successful" response.
Do this in either global.asax or in an implementation of IHttpModule
, in response to the PostAcquireRequestState
event (because that is the event that fires after the appropriate session - or lack thereof - has been set). You could also do it in a handler for BeginRequest
if you were already doing something there anyway. global.asax is easier to add in quickly, but modules are more easily re-used or set to work for certain sections of an application and not others.
Upvotes: 2