How to access value from code behind in global asax - asp.net

In my page I'm regenerating session id on every button click to go to the next page. I've already saved username in my session variable (session["uname"]=txtusername.text) in the time of log in. But as I'm regenerating new session id ,session["uname"] is having null reference because of new session id.That's why I want to set the session variable value using a Global.asax in session start function.
void Session_Start(object sender, EventArgs e)
{
session["uname"]=here;
}
But here in Global.asax page I'm unable access any value from my log in page..
The main problem is accessing any value in global.asax from code behind.
How can I solve this......Plz help......Thanking in advance..............

HttpContext.Current.Session["uname"]=here;

First don`t write business logic in Global.asax .
I want to point you out 3 basic things:
When session_start() called
How sessions are maintained
Where you should set your session variables.
For the following details I am assuming you have login.aspx, login.aspx.cs:
As you know HTTP is stateless protocol, so every request is new request.
So for every request session_start() will get executed.
When user request the resource for the first ever time, unique session will be generated, and cookie containing session Id will be sent to client.
For any further request from the user, HTTP client will pass the cookie to server, so user can be tracked by the server. This is how session works.
Now lets come to your code you are setting Session["uname"] in session_start() of Gloabl.asax, keep in mind that Globlax.asax is called before the page life-cycle begins
so it does not have access to page data.
Instade you should set your Session["uname"] in login.aspx.cs file. Here check if users credentials are correct then:
set Session["uname"]=value.
Now for every other request Session["uname"] for that user will be available. And you can also retrieve/update the values at session_start() of Global.asax too.

Related

Detect Session Expiry in Asp.Net MVC 5 Razor Application

I am developing Asp.Net MVC 5 Razor Application. I am maintaining separate table to maintain login information. When user logs in, I put 'true' in a field (IsLoggedIn) on success callback of login, in that table. When user logs out, I put 'false' in that field on success callback of logout module.
I am having one problem. If user does not press log out button, and its session is expired it gets log out. My success callback of logout is not called and 'IsLoggedIn' field in database still shows true for that user.
I am unable to find anything regarding how can I detect session expiry event and call my table updation function to put 'false' in 'IsLoggedIn' field to for user row?
Any Help?
Session timeouts can be handled in the Session_End event in your Global.asax, if your application using InProc SessionState mode(this is default in ASP.net if not specified)
void Session_End(object sender, EventArgs e) {
// perform your logic
}
before doing this remember one thing The event will be called, but not necessarily right after the timeout.
also take this into consideration that According to MSDN,the HttpSessionState.Timeout property has a setter and can be changed from within your application's code as well as permanently in the web.config
Hope this helps

Session State Can not be Saved, It was already Flushed by Application

In my Web Application, i am getting an error. "Session state has created session ID. But It can not save it because it was already flushed by application".
I googled for this issue and found that i have to store session id in Global.asax Session_Start Event.
string id = Session.SessionID;
But it was already exist in my application. I am not sure what else is causing issue. I was not using Response.Flush() also.
Can anyone please explain about this issue & fix for it.
That happens because sometimes (depending on the web.config configuration) the SessionID is not set in the cookie when Session_Start event executes in the global asax.
You encounter this error because at somepoint in the pagelifecycle a variable is set in the session. After the request ends, ASP.NET tries to set the SessionID too, but if the Request was flused (eg. this can be done by Response.Write or AJAX itself flushes the response) this exception will be thrown.
A simple fix would be (in the global.asax file):
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
//Ensure SessionID in order to prevent the folloing exception
//when the Application Pool Recycles
//[HttpException]: Session state has created a session id, but cannot
// save it because the response was already flushed by
string sessionId = Session.SessionID;
}

Session Log Out Issue

There is web application which is created on asp.net.
This application works perfectly when i run this on my local.
I have used session to store the userId of the user in the session.
In every page where i want only logged in user to be able to enter i have written code like.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["userID"] == null)
{
Response.Redirect("login.aspx");
}
}
}
So when session does not have userID user gets automatically redirected to login page.
I am facing two problems
1.When I deploy it to BigRock shared server.User automatically gets logged out in 5 minutes.It is defined session time out set in that server which I can not change. I do not want my user to get logged out automatically.
2.Payment Gateway is also integrated with this website and when the user clicks on check out .He gets redirected to payment gateway but when after entering his payment details and transaction completes when he gets back to response page ,he again automatically gets logged out whether 5 minutes was completed or not.This also works fine when I test this for the condition when I run this website on my local.
Every help is appreciated.Thank You So much in advanced!
Please let me know if you need any more clarification or source code.
Well, you can always try logging back the user based on the order-id received from PG. Since the response from PG is usually protected by checksum, you can rely on it's authenticity to carry back the user to your page. Just update your login session by using FormsAuthentication.SetAuthCookie method to re-login the user.
In your case since your directly assigning userdId to Session (IMHO, not the best way to manage logins though. Try searching for MembershipProvider), the steps are pretty straight forward.
Get the OrderId from PG response.
Fetch the associated userId from Orders table (For this you must have associated each user with their orders.
Save the userId in Session.
Redirect the user to secure page.
Why are we not asking for password? Because, responses from PG are usually protected by means of hashing and usually immune to tampering. So you can safely bet on the authenticity of the user redirected by PG.

how to change session id after login in asp.net

I have a website that's using forms authentication and membership. A user must have cookies enabled to use the site. I've been asked to change the code so that the session id is changed as soon as a user logs in. Aparently this will protect against a Session Fixation attack (http://en.wikipedia.org/wiki/Session_fixation). Does anyone know how I can change the session id without losing the whole session ? PHP has a specific method for doing this but I can't find a .NET equivalent.
Here's a blog post that talks about this:
ASP.NET does not directly support
functionality to regenerate a session
ID. See the documentation regarding
the issue here. There is a not-so
quick and dirty way to do it by
setting the ASPNET_SessionID value to
the empty string and redirecting so
that the value is regenerated.
I have answered a similar question at Generating a new ASP.NET session in the current HTTPContext. Basically we must change some of the SessionStateModule internal state to be able to regenerate session ID without losing objects in the Session. I used reflection to set the _rqId field to the new ID and _rqSessionStateNotFound to true. The downside is we must grant "Full Trust" to the Application.
This is a really old question I'm resurrecting, but here's the solution:
var manager = new SessionIDManager();
bool redirected, isAdded;
manager.SaveSessionID(System.Web.HttpContext.Current,
"5vonjb4mtb1of2fxvhjvkh5d", out redirected, out isAdded);
// sessionId now equals "5vonjb4mtb1of2fxvhjvkh5d"
var sessionId = Session.SessionID;
The method suggested in Microsoft's obsolete KB article 899918 works well even for .NET framework 4.5 Web Forms applications. Here is the archive of the article: https://www.betaarchive.com/wiki/index.php/Microsoft_KB_Archive/899918
How and why session IDs are reused in ASP.NET
Article ID: 899918
Article Last Modified on 9/8/2006
APPLIES TO
Microsoft .NET Framework 1.1
INTRODUCTION
This article describes how and why Microsoft ASP.NET session IDs are used.
MORE INFORMATION
The ASP.NET session state is a technology that lets you store server-side, user-specific data. Web applications can use this data to process requests from the user for which the session state was instantiated. A session state user is identified by a session ID. The session ID is delivered by using one of the following methods:
The session ID is part of a cookie that is sent to the browser of the user.
The session ID is embedded in the URL. This technique is also known as a cookie-less session.
Session IDs are a 120-bit random number that is represented by a 20-character string. The string is formatted so that it can be included in a URL and it does not have to undergo URL encoding. For example, the string may be used in cookie-less sessions. The most commonly used method of delivering session IDs is by using cookies to store the session IDs.
When a user first opens their Web browser and then goes to a Web site that implements ASP.NET session state, a cookie is sent to the browser with the name "ASP.NET_SessionId" and a 20-character value.
When the user browses within the same DNS domain, the Web browser continues to send this cookie to the domain for which it was sourced.
For example, app1.tailspintoys.com and app2.tailspintoys.com are both ASP.NET applications. If the user goes to app1.tailspintoys.com and then goes to app2.tailspintoys.com, both applications would use the same cookie and the same session ID to track the session state of the user within each application. The applications do not share the same session state. The applications only share the session ID.
Therefore, you can reuse session IDs for several reasons. For example, if you reuse session IDs, you do not have to do the following:
Create a new cryptographically unique session ID when you are presented with a valid session ID.
Create a new session ID for every ASP.NET application that is in a single domain.
When the Web application requires a logon and offers a log off page or option, we recommend that you clear the session state when the user has logged off the Web site. To clear the session state, call the Session.Abandon method. The Session.Abandon method lets you flush the session state without waiting for the session state time-out. By default, this time-out is a 20-minute sliding expiration. This expiration is refreshed every time that the user makes a request to the Web site and presents the session ID cookie. The Abandon method sets a flag in the session state object that indicates that the session state should be abandoned. The flag is examined and then acted upon at the end of the page request. Therefore, the user can use session objects within the page after you call the Abandon method. As soon as the page processing is completed, the session is removed.
When you use the in-process session state mode, these session state objects are stored in the HttpCache. The HttpCache supports a callback method when the following conditions are true:
A cache entry is removed.
The Session State Manager registers the Session_OnEnd event handler to be called when the cache entry is removed.
When the Session State Manager removes a session state object that resides in the cache, the HttpCache manager will call any registered callbacks. In effect, this behavior raises the Session_OnEnd event handler.
When you abandon a session, the session ID cookie is not removed from the browser of the user. Therefore, as soon as the session has been abandoned, any new requests to the same application will use the same session ID but will have a new session state instance. At the same time, if the user opens another application within the same DNS domain, the user will not lose their session state after the Abandon method is called from one application.
Sometimes, you may not want to reuse the session ID. If you do and if you understand the ramifications of not reusing the session ID, use the following code example to abandon a session and to clear the session ID cookie:
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
This code example clears the session state from the server and sets the session state cookie to null. The null value effectively clears the cookie from the browser.
When a user does not log off from the application and the session state time-out occurs, the application may still use the same session state cookie if the browser is not closed. This behavior causes the user to be directed to the logon page and the session state cookie of the user to be presented. To guarantee that a new session ID is used when you open the logon page (login.aspx), send a null cookie back to the client. To do this, add a cookie to the response collection. Then, send the response collection back to the client. The easiest way to send a null cookie is by using the Response.Redirect method. Because the cookies collection always has a value for the ASP.NET_SessionId, you cannot just test if this cookie exists because you will create a Response.Redirect loop. You can set a query string on the redirect to the logon page.
Or, as illustrated in the following code example, you can use a different cookie to tell if you are already redirected to the logon page. To help enhance security and to make sure that no one tries to open the logon page by using a second cookie together with the ASP.NET cookie, the following code example uses the FormsAuthentication class to encrypt and decrypt the cookie data. Then, the code example sets a 5-second time-out.
private void Page_Load(object sender, System.EventArgs e)
{
if( !IsPostBack && ( Request.Cookies["__LOGINCOOKIE__"] == null || Request.Cookies["__LOGINCOOKIE__"].Value == "" ) )
{
//At this point, we do not know if the session ID that we have is a new
//session ID or if the session ID was passed by the client.
//Update the session ID.
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
//To make sure that the client clears the session ID cookie, respond to the client to tell
//it that we have responded. To do this, set another cookie.
AddRedirCookie();
Response.Redirect( Request.Path );
}
//Make sure that someone is not trying to spoof.
try
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt( Request.Cookies["__LOGINCOOKIE__"].Value );
if( ticket == null || ticket.Expired == true )
throw new Exception();
RemoveRedirCookie();
}
catch
{
//If someone is trying to spoof, do it again.
AddRedirCookie();
Response.Redirect( Request.Path );
}
Response.Write("Session.SessionID="+Session.SessionID+"<br/>");
Response.Write("Cookie ASP.NET_SessionId="+Request.Cookies["ASP.NET_SessionId"].Value+"<br/>");
}
private void RemoveRedirCookie()
{
Response.Cookies.Add(new HttpCookie("__LOGINCOOKIE__", ""));
}
private void AddRedirCookie()
{
FormsAuthenticationTicket ticket =
new FormsAuthenticationTicket(1,"Test",DateTime.Now,DateTime.Now.AddSeconds(5), false,"");
string encryptedText = FormsAuthentication.Encrypt( ticket );
Response.Cookies.Add( new HttpCookie( "__LOGINCOOKIE__", encryptedText ) );
}

ASP.NET global events

which event is the most suitable to check for Session expired? i'm trying to trap each server request, and if Session is null, redirect to a different page.
You can determine if a new session is being created by hooking Session_OnStart - http://msdn.microsoft.com/en-us/library/ms178583(VS.80).aspx
You can handle the Session_OnStart
event by adding a subroutine named
Session_OnStart to the Global.asax
file. The Session_OnStart subroutine
is run at the beginning of a request
if the request begins a new session. A
new session will be started if a
request is made that does not contain
a SessionID value or if the SessionID
property contained in the request
references a session that has expired.
This will tell you effectively when a new session is being created, regardless of if the user just arrived or the session had expired.
It would be hard to reliably differentiate between both scenarios. I guess you could try to get a hold a the session id in the either the session cookie or embedded in the url (cookieless), but you would need to check it before getting to the above event, and later check whether the request had a session id originally. Check if you can get to the session id in the cookieless version, because it is stripped out of the urls asp.net gives you (not sure if early in the lifecycle you get to see it).
This is often best achieved by using a base Page class for all otehr classes, and implementing this in the Page_Load method.
Use BasePage class, which inherits from Page class. Let every aspx page inherits that BasePage class. In BasePage class, override OnInit event, in which you can check for Session or Cookie, and redirect user to login page (for example).
I use this approach for all mine webforms apps, because it's easy to implement and use.

Resources