Progromatically get SessionId Cookie name used in an asp.net application

09 Sep 2013 .Net, C#, MVC No Comments

The default name for the SessionId cookie in an Asp.Net application is ASP.NET_SessionId, but this can be changed in the web.config, e.g.

I wanted to get the name of the SessionId cookie for the web app that was implementing my class library. I knew the dll would be implemented by many other future projects, written by many other developers, so I could not rely on any standard naming convention. I needed to know what the SessionId cookie was called in any situation.

Progromatically getting the SessionId cookie name would also be good to use in all situations as you never know when another developer working on the same project may decide to change something like the SessionId cookie name; this could easily result in broken code. That developer might even be you!

So here is the method I wrote to return the SessionId cookie name, along with the extra references you will need for this method:

I can now use this to get the cookie name, and if it is null I can create and save my own SessionId cookie.

Thank you to Claudio Redi on StackExchange for his code which I adapted.