What is the difference between these two HttpContext.Current.Session and Session - asp.net 4.0

MonsterMMORPG picture MonsterMMORPG · Oct 31, 2011 · Viewed 31.4k times · Source

What is the difference between these 2 piece of codes.

HttpContext.Current.Session["myvariable"]
Session["myvariable"]

asp.net 4.0 and C# 4.0

Answer

Kasaku picture Kasaku · Oct 31, 2011

They're effectively the same, in that they will access the same Session data.

The reason you can call Session in your code-behind is because ASP.Net pages by default extend the System.Web.UI.Page type. This has a Session public property. If you look at the code for this in Reflector you can see that it just calls HttpContext.Current.Session itself (through its own Context property).

In other classes you will not have access to that property, but you can use HttpContext.Current.Session to access the session data instead, as long as you're running in the context of a web application.