Why Session End is called on App Start up? - c#

I wanna free some DB resources and set few flags when User Session Ends in ASP.NET Site. But when I write my code to access session variables in Session End method of Global.asax file, its getting called everytime the App starts, Why this weird behavior?
Secondly, I want to access user specific session variables and free them up in DB on Session End. Thus I am using few session Variables where I am setting them in a webmethod on a Page and trying to access them on Session End. But since Session end is being called on App start up its always throws Null reference exception.
Here is mycode. for Setting up a variable in Webmethod in a .aspx page
[WebMethod(EnableSession=true)]
protected void checkUser()
{
Session["TestObject"] = "Hello I am session";
}
In my global.asax file I am trying to access as follows in Session_End method
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
if (this.Context.Session != null && this.Context != null)
{
string k = this.Session["TestObject"].ToString();
}
}
I even tried HttpContext.current.Session etc.. but none worked. All are throwing exception as Session end is called on App start up and even when session timed out.

Related

ASP.net MVC 5 Session is not clearing after calling Abandon()

MVC noob here.
I currently have this code that fires off my HomeController when a page loads via AJAX:
namespace ETTData.Controllers
{
public class HomeController : Controller
{
[HttpPost]
public ContentResult clearSessions()
{
var currentSession = System.Web.HttpContext.Current.Session;
System.Diagnostics.Debug.WriteLine("BEFORE: " + currentSession.Timeout);
currentSession.Abandon();
//currentSession.RemoveAll();
//currentSession.Clear();
System.Diagnostics.Debug.WriteLine("AFTER : " + currentSession.Timeout);
return new ContentResult { Content = "OK", ContentType = "text/plain" };
}
}
}
The output of the debug.WriteLine is:
BEFORE: 35
AFTER : 35
So as you can see it has 35 on the BEFORE but also has 35 for the AFTER when it shouldnt equal anything since I used currentSession.Abandon(); prior to calling that output.
I am setting the session timeout via the Global.asax.cs file:
namespace ETTData
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session.Timeout = 35;
}
}
}
So saying all that - I'm at a loss as to why its not clearing the session...
Yea that's a good one that got me too in WebForms a long time ago.
The issue is, that your session is bound to a session cookie.
The cookie is transmitted in the request and response headers, which means via the HTTP protocol. The HTTP protocol is stateless, and therefore, it can't remove a cookie until after a response has been sent.
When you call session.Abandon, the session data will be abandoned at the same time as the cookie is abandoned at the client. Which means the frameworks marks the session data as "to be cleared after the response has been sent", which is after response.end. At response.end (which will be called after ContentResult.ExecuteResult), the framework will then clear the session. Subsequently it will call the Session_End event.
Session.Clear removes items immediately, but it will not remove the session cookie - therefore it also doesn't end the session, and it will not call the Session_End event - which is because it doesn't expire the session cookie.
Think of it as async-function.
You called abandon, but it's not yet executed.
As the others told you, if you need the session cleared immediately, call session.clear after session.abandon.
But if you start another session after you called session.abandon, you'll run into a very sharp knife.
Basically, you should never use sessions.
If you want to access "session" data without a detour into the database, you should store the information in an encrypted and asymmetrically-signed cookie, which you can bind to a session-lifetime, if you want to, but you don't have to. Google JWT for more information. I would bind such data into your auth-cookie. That way, there's no need for >1 cookies. The default timeout of 20 minutes in ASP.NET is a pretty bad thing. Your session data shouldn't expire until your authentication has.
Also, be careful what you write into your session.
If you just store user information there, that's fine.
But if you store state information there, you'll have a problem, because I can open multiple tabs of your site at once, and then the state from tab2 will overwrite the state of tab1. You have ONE session per domain, not one per tab.
Have a look at this question to find your answer.
In Short: Session.Abandon destroys the session but doesn't clear it's values. This happens when the request ends. Session.Clear clears everything from the session but doesn't destroy it.

Maintaining session in a class C#

I am trying to maintain session in a class for MVC application. Below is the code which i used get and set session in a variable. But whenever i am accessing this variable after set, it is giving null.
public static class MySession
{
public static string MyVar
{
get
{
return HttpContext.Current.Session["MyVar"] == null ? "" : HttpContext.Current.Session["MyVar"].ToString();
}
set
{
HttpContext.Current.Session["MyVar"] = value;
}
}
}
And I used to set as
MySession.MyVar="testData";
But when i access
string str = MySession.MyVar;
it gives null value. Does anybody know why my session is not stored?
Session variables are very much exposed to being null, that is each time a new session is created by user, browser, network or application itself. That is why, it is very much recommended to wrap it around with if...else block.
if(Session["key"] != null) {
// Variable exists for the session
// use variable
} else {
// Variable doesn't exist in the session
// create and user variable
}
However, if still you always get a null, then you should check what is going wrong. My bet is that there is some other code or process that terminates the previous sessions and restarts them. You should know you can programmatically also remove all sessions, that might also cause this problem.
Also, Session variables can be used and served using a class, there is no problem in that. Just make sure that the collection Session isn't being refreshed.
My guess is you have not enabled session state.
<system.web>
<sessionState mode="InProc" timeout="60"/>
<system.web>
Session state is disabled by default in MVC and is generally not recommended unless absolutely necessary.

Response is not available in this context in asax file

I have a login page that works only with Firefox. It does not work with any other browsers.
When I checked the event log, I saw a "response is not available in the current context". It tells me that the error is in the global.asax file, at the response.redirect line:
void Session_End(object sender, EventArgs e)
{
Response.Redirect("~/Login.aspx?li=1");
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
What could be the problem?
I have tried httpcontext.Current as suggested but then I get a Null Reference Exception, Object Reference not set to an instance of an object
Thank you.
Try using HttpContext.Current.Response it should definitely work.
Did you try using HttpContext.Current.Response?
Happy coding!!

Session losing its state after javascript function call

We are using Sharepoint 2007
We initialising the session variable on page load
We have one javascript function as mentioned below
function backclick()
{
__doPostBack('btnCaseSearch', 'Click');
alert('Select the Search Criteria.');
}
but after calling this we are losing session value.
If we remove __doPostBack('btnCaseSearch', 'Click');
then alert is displaying each time when page gets load but session is not losing its value.
How to maintain session pls help or suggest some alternative to _doPostBack()
the sceneario is like this
below javascript function
function backclick()
{
__doPostBack('btnCaseSearch', 'Click');
alert(result not found.');
}
function check()
{
var btn ="<%=Session["search"]%>";
if(btn == "true")
{
do something
}
else
{
else part
}
Below server side code
Page_Load()
{
//initialise session variable
session["search"] = "true";
}
btnSearch_click()
{
if(result not found)
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(),"page_index_script1", "backclick();", true);
}
}
so when backclick() javascript function gets called at that time session is losing its state but if backclick() doesn't get called then code works perferctly
Thanks
Something which jumped out at me:
We initialising the session variable on page load
Is this page load server-side?
Each time you _doPostBack will cause pageLoad to execute, so I believe this is where you're overwriting your session variable.
The only way the session will loose it's state is:
If it gets overwritten or removed (use a breakpoint to check you're not setting it twice!)
The browser is not surrendering the cookie on subsequent requests
Check both of these and if your problem isn't solved post what you found.

FormsAuthentication.SignOut throwing NullReferenceException

This problem seems related to this post, but I was not able to infer a solution from the thread.
I noticed this code in an application I inherited (after noting in a log file that an exception was being eaten):
protected void Session_End(object sender, EventArgs e)
{
try
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
//if (this.Context.Handler is IRequiresSessionState || this.Context.Handler is IReadOnlySessionState)
//{
// FormsAuthentication.SignOut();
// FormsAuthentication.RedirectToLoginPage();
//}
}
catch (Exception ex)
{
this.GetType().GetLogger().Error(ex);
}
}
I am wondering a few things. First, how is SignOut throwing a null reference exception? Is it an exceptional case, or am I doing something inherently wrong in my program? Next, what should I be testing against to head-off this exception before it is thrown?
15:51:57,288 [13] ERROR ASP.global_asax - System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.Security.FormsAuthentication.SignOut()
at MvcApplication.Session_End
Thanks
It's important to realize that Session_End doesn't get necessarily executed in the the context of an HTTP request. It may run when a session times out. You cannot send anything to the client at that time, because it simply isn't there anymore!
Consequently, you should not try to delete the forms authentication cookie in Session_End. If you want, you should do that sooner, when a "Sign Off" button is clicked somewhere in your application. If you need a user's forms authentication ticket to expire after a timeout occures, you should simply set the cookie expiration time appropriately (possibly equivalent to session timeout value) in the config file.

Categories

Resources