ASP.NET - Get SessionID while in from the Global.ASAX - asp.net

I'm recording the session start times from when people log into my .NET 2.0 web application, but I'd also like to record the Session ID. Can someone give me some example code on how to accomplish this (how to access the Session ID from within the Global.ASAX).
If you need any additional info just let me know.

HttpContext.Current.Session.SessionID
Edit to show null test:
if ((HttpContext.Current != null) && (HttpContext.Current.Session != null) {
id = HttpContext.Current.Session.SessionID
}

You can get at it quite simply with HttpContext.Current.Session.SessionId as you probably already know. You need to be on or after Application_AcquireRequestState before the session state has been loaded, and session state is also only loaded when the requested resource implements IRequiresSessionState. You can see a list of all the events in global.asax here: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5771721.html and read more about IRequiresSessionState here: http://msdn.microsoft.com/en-us/library/system.web.sessionstate.irequiressessionstate.aspx

Write to the session the datetime and sessionid at the moment of the first request following ASP.NET's identifying the user's session.
protected void Application_PreRequestHandlerExecute(object sender, EventArgs eventArgs) {
var session = HttpContext.Current.Session;
if (session != null) {
if (session["foo"] == null) {
session["foo"] = DateTime.Now.Ticks + "|" + session.SessionID;
}
}
}

Related

How to detect session expire programmatically

i search google and found many answers for detecting session expiry programmatically. this is code which i saw everyone use it
global.asax
---------------
protected void Session_Start(object src, EventArgs e)
{
if (Context.Session != null && Context.Session.IsNewSession)
{
string sCookieHeader = Request.Headers["Cookie"];
if (null != sCookieHeader && sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)
Response.Redirect("/Session/Timeout");
}
}
i have few question on the above code
1) when session expire then how Context.Session will not be null?
2) what is the meaning of this line Request.Headers["Cookie"];
looking for good discussion. thanks
You can use the Session_End method in global.asax file
void Session_End(Object sender, EventArgs E) {
// Clean up session resources
}
1) when session expire then how Context.Session will not be null?
Your code triggers when a user comes back to the server with an expired session.
The session object in this code is the new empty session which is beginning.
Remember you are in Session_Start, not in Session_End.
2) what is the meaning of this line Request.Headers["Cookie"];
The cookie contains the session's id. If a user is requesting a ressource, providing a session id, and Session_start is triggered, that almost certainly means that the session id refers to an expired session object. A specific message is then displayed to the user.

Why HttpContext.Current.Session is null in Global.asax?

I'm using VS2010 and created a simple asp. web forms application, using Development Server to test it.
I try to store user data - queried from sql server - in the session, since I don't want to access database in every request. I'm using the 'Application_AuthenticateRequest' and the 'Session_Start' methods.
First round:
AuthenticateRequest called. The following code ran:
public static void Initialize(string login_name, bool force_refresh)
{
HttpSessionState Session = HttpContext.Current.Session;
object o = Session == null ? null : Session["EMPLOYEE_DATA"];
if (force_refresh || o == null || o.GetType() != typeof(Employee) || (o as Employee).login_name!= login_name)
{
_current = UIManager.GetEmployee(login_name);
if (Session != null)
{
Session["EMPLOYEE_DATA"] = _current;
}
}
else
{
_current = (Employee)o;
}
}
The _current variable is a private static field published through a static property.
In the first round the Session is null, and I think it's ok because the Session_Start not called yet.
The Session_Start looks like this:
protected void Session_Start(object sender, EventArgs e)
{
Session["EMPLOYEE_DATA"] = EmployeeFactory.Current;
}
In the next round the Session_Start is not called of course but in the AuthenticateRequest I can't access to the session. The HttpContext.Current.Session is null and the this.Session reference throw a HttpException says the "Session state is not available in this context".
However I can access the Session from any of the page_load events but it's a bad practice I think that I put authentication every page_load.
Any idea how can I access to the Session?
Thanks for advice,
Péter
You're not able to use Session on the Application_AuthenticateRequest becauase it's not bound at that moment.
I think you're able to use the event Application_AcquireRequestState.
try to use the below code in page_Load
Response.AppendHeader("Refresh", Convert.ToString(Session.Timeout * 15) + ";
URL=SessionExpPage.aspx");

ASP.NET Session in Global.asax

Session in Application_AuthenticateRequest method in Global.asax is always null.Ive already try:
this.Session,HttpContext.Current.Session
always null.
protected void Application_AuthenticateRequest()
{
string userRole = string.Empty;
if (Request.IsAuthenticated)
{
if (this.Session["UserRole"] == null)
{
InsertSessionValue();
}
userRole =Session["UserRole"].ToString();
HttpContext.Current.User = new GenericPrincipal(User.Identity, new string[] {userRole});
}
}
Ive also try to use Cache,but it doesnt work because i need unique information for each user.
How to use Session in Global.asax?Is HttpApplication Application property unique for each user?
You just can't use Session at this point in the request lifecycle, it isn't available/populated yet, if you want to use it you'll need to move to an event later in the lifecycle, for example PostAcquireRequestState.

Session expiration issue in ASP.NET MVC

Hi I have some issues with ASP.NET MVC session state which is not expiring after I implement the following piece of code and put the attributes over the methods.
public sealed class SessionActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
//Check if session is supported
if (ctx.Session != null)
{
//Check if the session is new
if (ctx.Session.IsNewSession)
{
//If it says it is a new session but an existing cookie exists
//then it must have timed out
string sessionCookie = filterContext.HttpContext.Request.Headers["Cookie"];
if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET_SessionId", StringComparison.OrdinalIgnoreCase) >= 0))
{
//Redirect to the login page
ctx.Response.Redirect("~/Home/Index", true);
ctx.Response.End();
}
}
}
base.OnActionExecuting(filterContext);
}
}
The issue is that the Redirection request is not executing and the Action which has SessionActionFilter Attribute executes. This method uses session variables which are expired and results in error.
Can anybody tell what I am missing?
Thanks a lot in advance!!
We are storing some data which is used in our views!! One more update I was able to run this piece of code which is now working fine. However, I am a bit skeptical about the use of cookies and need to transform this code to work for cookieless sessions also. How is this possible?

ASP.NET 2.0: Problem in Httpcontext.current.session.add()

Can anybody help me to find out solution of following problem.
In ASP.NET website: at Application_OnPostAuthenticate() event, whatever code i write is executed for every request. therefore due to this customidentity object, countryid and weatherid is called everytime for each request (call for database for value). It effect response time of page and unneccessary code execute.
void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
{
// Get a reference to the current User
IPrincipal objIPrincipal = HttpContext.Current.User;
// If we are dealing with an authenticated forms authentication request
if ((objIPrincipal.Identity.IsAuthenticated) && (objIPrincipal.Identity.AuthenticationType == "Forms"))
{
CustomPrincipal objCustomPrincipal = new CustomPrincipal();
objCustomPrincipal = objCustomPrincipal.GetCustomPrincipalObject(objIPrincipal.Identity.Name);
HttpContext.Current.User = objCustomPrincipal;
CustomIdentity ci = (CustomIdentity)objCustomPrincipal.Identity;
HttpContext.Current.Cache["CountryID"] = FatchMasterInfo.GetCountryID(ci.CultureId);
HttpContext.Current.Cache["WeatherLocationID"] = FatchMasterInfo.GetWeatherLocationId(ci.UserId);
Thread.CurrentPrincipal = objCustomPrincipal;
}
}
To solve this problem when i try tochange code as follows
HttpContext.Current.Session.Add("test", FatchMasterInfo.GetWeatherLocationId(ci.UserId);); in place of cache i found foolowing error
"Object refrence not set to the instance of object"
I don't know whether we can store session variable inside Application_OnPostAuthenticate() event or not?
You could try doing this a bit later in the request, such as in the PreRequestHandlerExecute event:
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
IPrincipal objIPrincipal = HttpContext.Current.User;
if ((objIPrincipal.Identity.IsAuthenticated) && (objIPrincipal.Identity.AuthenticationType == "Forms"))
{
HttpSessionState session = HttpContext.Current.Session;
CustomPrincipal objCustomPrincipal = new CustomPrincipal();
if (session[objIPrincipal.Identity.Name] == null)
{
// get data from database or wherever
objCustomPrincipal = objCustomPrincipal.GetCustomPrincipalObject(objIPrincipal.Identity.Name);
CustomIdentity ci = (CustomIdentity)objCustomPrincipal.Identity;
Object countryID = FatchMasterInfo.GetCountryID(ci.CultureId);
Object weatherLocationID = FatchMasterInfo.GetWeatherLocationId(ci.UserId);
// save in session (not cache as cache is application-wide, not per-user):
session.Add(objIPrincipal.Identity.Name, objCustomPrincipal);
session.Add(objIPrincipal.Identity.Name + "_CountryID", countryID);
session.Add(objIPrincipal.Identity.Name + "_WeatherLocationID", weatherLocationID);
}
else
{
// already have custom principal object in session
objCustomPrincipal = (CustomPrincipal)session[objIPrincipal.Identity.Name];
}
// set the custom principal object to context/thread
HttpContext.Current.User = objCustomPrincipal;
Thread.CurrentPrincipal = objCustomPrincipal;
}
}
You probably don't want to access the session in any event that happens in every request. Some requests don't even have session (for instance, a lot of web service calls, or calls to WebResource.axd that load static resources).
Before adding value to cache object, check if it already exists in the cache.
You might not have session state enabled. Does it work anywhere else (like in a web form's display)?
Look for a <sessionState> element under your system.web element in web.config make sure it's turned on (set it to InProc unless you have a web farm).

Resources