Click here to Skip to main content
12,699,214 members (26,206 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


8 bookmarked

Cookieless Session in ASP.NET

, 26 Jul 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Cookieless session in ASP.NET


There are various reasons to adopt cookieless session. Recently, I implemented cookieless session and in that process, I went through many articles on the internet, but none of them have gone in depth to bring it all together.

To implement cookieless sessions, you don't have to modify your programming model—a simple change in the web.config file does the trick. But with that can come uncovered scenario and you would end up spending considerable time fixing it up just like I did. So let's get started with what and how it has to be changed to make cookieless work for you with no issues.

Now let us go through the steps one by one:

Step 1: Adjust the web.config file

Interestingly enough, you don't have to change anything in your ASP.NET application to enable cookieless sessions, except the following configuration setting.

<sessionState cookieless="true"
                        <authentication mode="Forms">                     
                        <forms loginUrl="Login.aspx" protection="All" timeout="30"
                            name=".ASPXAUTH" path="/" 
                            requireSSL="false" slidingExpiration="true"
                            cookieless="UseUri" enableCrossAppRedirects="true"/>                   

Step 2: Adjust all of the URL navigations in aspx files

Be careful, the following code breaks the session:

<a runat="server" href="/test/page.aspx">Click</a>

To use absolute URLs, resort to a little trick that uses the ApplyAppPathModifier method on the HttpResponse class. The ApplyAppPathModifier method takes a string representing a URL and returns an absolute URL that embeds session information.

<a runat="server"
href=<% =Response.ApplyAppPathModifier("page.aspx")%>

Step 3: Adjust all of the URL navigations in aspx.cs files

If the URL is set in the code, you need to do it in the following way:

this.Tab2.Url = Response.ApplyAppPathModifier("Page.aspx");

Step 4: Create HttpModule to rewrite your incoming URL for enabling cross domain posts

using System;
using System.Collections.Specialized;
using System.Web;
using System.Web.SessionState;
using System.IO;
using System.Text;

namespace CustomModule
  public sealed class CookielessPostFixModule : IHttpModule
    public void Init (HttpApplication application)
      application.EndRequest += new
    private string ConstructPostRedirection(HttpRequest req,
                                            HttpResponse res)
      StringBuilder build = new StringBuilder();
  "<html>\n<body>\n<form name='Redirect' method='post' action='");
      build.Append("' id='Redirect' >");
      foreach (object obj in req.Form)
  "\n<input type='hidden' name='{0}' value = '{1}'>",
  "\n<noscript><h2>Object moved <input type='submit'
      <script language="'javascript'">
      // -->
      return build.ToString();
    private bool IsSessionAcquired
        return (HttpContext.Current.Items["AspCookielessSession"]!=null && 
    private string ConstructPathAndQuery(string[] segments)
      StringBuilder build = new StringBuilder(); 

      for (int i=0;i<segments.Length;i++)
        if (!segments[i].StartsWith("(") 
                 && !segments[i].EndsWith(")"))
      return build.ToString();
    private bool IsCallingSelf(Uri referer,Uri newpage)
      if(referer==null || newpage==null)
        return false;
      string refpathandquery = ConstructPathAndQuery(
      return refpathandquery == newpage.PathAndQuery;
    private bool ShouldRedirect
        HttpRequest req = HttpContext.Current.Request;

        return (!IsSessionAcquired
                    && req.RequestType.ToUpper() == "POST"
          && !IsCallingSelf(req.UrlReferrer,req.Url));
    private void Application_EndRequest(Object source, EventArgs e)
      HttpRequest req = HttpContext.Current.Request;
      HttpResponse res = HttpContext.Current.Response;
      if (!ShouldRedirect) return;
      char[] chr = ConstructPostRedirection(req,res).ToCharArray();
    public void Dispose()

For the above to be effective, make the below change to your web config:

   <add type="CookielessPostFixModule, OurModule"
              name="CookielessPostFixModule" />

Points of Interest

For the above, I have referred to and, but there were issues which I have fixed and mentioned there as well as the purpose of having it here is to make sure someone who gets into a condition like mine gets clean material.

If you find some other thing, please let me know or feel free to edit.

Happy programming guys! :)


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Pandey Vinay
India India
No Biography provided

You may also be interested in...

Comments and Discussions

Questioncookieless session--role of server Pin
asian12323-Jan-15 1:59
memberasian12323-Jan-15 1:59 
GeneralMy rating is 4. Pin
Goel Himanshu2-Aug-14 1:11
professionalGoel Himanshu2-Aug-14 1:11 
QuestionURL copy issue Pin
Member 1058724813-Feb-14 22:12
memberMember 1058724813-Feb-14 22:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170118.1 | Last Updated 27 Jul 2013
Article Copyright 2013 by Pandey Vinay
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid