How to generate a unique session id for an ASP.NET application

less than 1 minute read

It is often useful to be able to track a user session through your ASP.NET application whilst avoiding the use of server-side session state. The following code generates a session cookie on the first request which will then be propagated to subsequent requests until you either clear the cookie or the user closes their browser.

using System;
using System.Web;
namespace Sample {
 public class SessionModule : IHttpModule {
  #region IHttpModule Members
  public void Init(HttpApplication context) {
   context.AuthenticateRequest +=<br></br>     new EventHandler(OnAuthenticateRequest);
  }<br></br>  public void Dispose() { }
  #endregion<br></br><br></br><br></br>  #region Event Handler
  private void OnAuthenticateRequest(object sender,EventArgs e) {
   HttpContext ctx = HttpContext.Current;
   HttpCookie cookie = ctx.Request.Cookies["SampleSession"];
   if(cookie==null) {
    ctx.Response.Cookies.Add(<br></br>     new HttpCookie("SampleSession",Guid.NewGuid().ToString()));
   }
  }
  #endregion
 }
}

You then need to add the HttpModule into the application in your web.config file as follows:

<httpModules>
  <add<br></br>    type="Sample.SessionModule,SampleSession"<br></br>    name="SessionIdentification"<br></br>  />
</httpModules>

where SampleSession is the name of the assembly that the class is compiled into.

Updated: