In this blog, I will show how to change the Assigned session Id programmatically.
You may ask : why I need to change the automatically generated the user session id ? well there is many possible reasons like :
- You may use the session ID to track the User activities or to implement audit trails in your system.
- Preventing Session Hijacking by generating a new session id after the user logged in.
- Removing the user session after logging out.
There could be more reasons that I don't know about them , if you know more reasons feel free to post it in the comments section .
Changing the Session id is an easy task in asp.net.You just need to use SessionIDManager class.
The class contains a lot of helpful methods ,I will list some of them :
- CreateSessionID : returns a unique session identifier that is a randomly generated number encoded into a 24-character string.
- GetSessionID : gets the session-identifier value from the current Web request.
- SaveSessionID : saves a newly created session identifier to the HTTP response.
The rest of methods and class members can be found here.
I will now show a simple code that will print the Current SessionId and Create a new session id and save it to the context.
[Code provided in C# ]
SessionIDManager Manager = new SessionIDManager();
string NewID = Manager.CreateSessionID(Context);
string OldID = Context.Session.SessionID;
bool redirected = false;
bool IsAdded = false;
Manager.SaveSessionID(Context, NewID,out redirected, out IsAdded);
Response.Write("Old SessionId Is : " + OldID);
Response.Write("<br/> New Session ID Is : " + NewID);
Response.Write("<br/> Session Id did not saved : ");
Hope it helps.