Tuesday, July 1, 2008

Custom SessionID In ASP.net 2.0

By default asp.net 2.0 create sessionid like this kidt1m55iyqcx2vrtkn3z0ba. But requirement is such that you need to use your own algorithm to generate sessionid. For this pupose you have to create class that inherit from SessionIDManager class and override it CreateSessionID and Validate methods.
For Example : I want to use GUID as sessionid .
public class CustomSessionID : System.Web.SessionState.SessionIDManager
{
public override string CreateSessionID(HttpContext context)
{
return Guid.NewGuid().ToString();
}
public override bool Validate(string id)
{
try
{
Guid idtest = new Guid(id);
if (idtest.ToString() == id)
return true;
}
catch
{
return false;
}
return false;
}
}

You can also use DateTime.Now().Ticks as SessionID, or any custom string as a sessionid.

This is very useful case when you want to functionality like same sessionid generate for sameuser.

You also have to set web.config sessionStat Section in following manner. Here i assume that above class present in App_code directory . but you can create class library and refrence that class in sessionState session.

web.config setting.

<sessionState sessionIDManagerType="CustomSessionID,App_code" >
</sessionState>