I have a strange problem in ASP .NET MVC 4. In AccountController I am doing redirects on certain actions and put data into TempData (which is stored in Session) before that:
[AllowAnonymous]
public ActionResult Activate(string token)
{
new CustomSignupService().Activate(token);
TempData["Message"] = "User was successfully confirmed";
return RedirectToAction("Message", "Home")
}
Now I know I could just return shared Message view in this case, but this is just a code sample to reproduce the problem.
CustomSignupService.Activate does a db lookup via NHibernate and updates user in transaction (user activation). Sometimes (lets say 1/5 tries in 5 minutes) TempData does not make it throught the redirect, so I added logging into Session_End and noticed that session ends when RedirectToAction is invoked. Right after that Session_Start is invoked but of course TempData is gone.
Session has default timeout (20min) and controllers use SessionStateBehavior.ReadOnly
Any ideas?
UPDATE
Step 1: It's not Application Pool recycling (I turned on all General Recycle Event Log entries on Application pool and checked event log, after session restarts but recycle is not causing it)
I had a problem with Session being lost. I used Fiddler and noticed that there was a duplicate ASP.NET session cookie with a blank value. I don't know how it got there. So a new session was created on every request. I deleted that duplicate cookie and the problem was solved.
Other unlikely reasons are:
IIS process recycle
Session.abandon being called
modifying bin folder or web.config causing app restart
Check out this page:
Losing Session State
I don't know ASP.NET MVC but in the dark centuries I used ASP.NET without MVC. I struggled several times with unexpected session ends. Most of the time it was caused by some simple things which are described in the article http://www.c-sharpcorner.com/uploadfile/technoNet/session-timeouts-causes-and-remedies/
Sometimes the server has entries in the event log that gives you a little bit more information.
And some other solutions might be
ASP.NET Session ending abruptly
random IIS session timeout
Related
I have one loginController With Index Mathod as
public ActionResult Index(string something)
{
Session.Abandon();
Session["ActiveUser"] = _user;
return RedirectToAction("All", "User");
}
and UserContoller as
public ActionResult All()
{
var _currentUser = ((AuthUser)Session["ActiveUser"]);
}
the problem is when redirect Happens the session state resets, I am not able to understand why ?
any help or resource will be appreciated.
Edit
I had also written Session.Abandon(); in the start when I removed that from I code it started working fine.
Yeah, that would explain it. Calling Session.Abandon queues the Session for destruction/removal and executes it when your initial request (before the redirect starts) finishes processing. So anything you do to Session (including TempData) in that initial request is essentially ignored because the entire session including changes is discarded. From the documentation.
When the Abandon method is called, the current Session object is queued for deletion but is not actually deleted until all of the script commands on the current page have been processed. This means that you can access variables stored in the Session object on the same page as the call to the Abandon method but not in any subsequent Web pages.
there is no special configuration of Session in the webconfig #Igor
Then the Session state is not enabled which is why you can't retrieve anything from Session or TempData. You need to configure the session state in the web.config. If you are only using this for TempData you can configure it for InProc. If you want to configure long term storage (data available across multiple requests) and you have multiple servers (ie. web farm) that can handle requests you should look at configuration using a store like Sql Server.
You can make the configuration changes either directly in the web.config (see SessionState documentation)
<sessionState mode="Off|InProc|StateServer|SQLServer"
cookieless="true|false"
timeout="number of minutes"
stateConnectionString="tcpip=server:port"
sqlConnectionString="sql connection string"
stateNetworkTimeout="number of seconds"/>
Or using IIS (see screenshot below).
I don't understand the notion of session for webservices. In one hand you can allow session in DataAnnotation like that :
[WebMethod(EnableSession = true)]
In the other and you can configure the session state in IIS :
So I put Session State in process and set the delay for 20 minutes.
Then in my webservice I try to get the session ID like that :
return HttpContext.Current.Session.SessionID
I use a winform to get this information and call the webservice.
And the session ID Change at every call. I don't understand why, beaucoup SessionState is set to 20 minutes...
May I'm in wrong way ? Can you explain me ?
Is SessionID correspond to the Session State in IIS ?
There must be something that connects the request to a particular session. Usually a cookie is used for that. This cookie is sent along with the response, so the calling application must remember that cookie and send it along with the next request. Without cookie the request is handled as if it's a new session.
A browser handles this by default (unless specifically switched off), for an other application you need to do cookie management yourself. For this you need to use a single CookieContainer that will be shared among your requests.
See the link in the answer by Marius for more details.
I was thinking of a solution, but then I found this post :
How to keep session alive between two calls to a web service in a c# application?
I hope this helps.
If you want to keep your sessionID same througout users session life time you should add a global.asax file to your web project and implement Session_Start method.
Please check this link:
https://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.sessionid.aspx
I want my web page to close when SessionState timeout occures. This is my code in my web config:
<system.web>
<sessionState timeout="1" mode="InProc"/>
</system.web>
I set to 1 minute for testing purposes. The following is my Global.asax code:
protected void Session_End(object sender, EventArgs e)
{
Response.Redirect("~/LogOut.aspx");
}
I put a label on one of the pages in order to check the session timeout, this is the code in the Page_Load event:
lblSession.Text = "SESSION TIME: " + Session.Timeout.ToString();
When I enter the site and come to this page the label shows SESSION TIME: 1, but after 1 minute I don't get redirected to the LogOut page and the present page is still fully active and working, apparently meaning that the session has not been terminated.
I am working in Visual Studio 2008 thru the development server so suggestions I've seen relating to IIS settings don't seem to be relevant at this stage.
Please help!
HTTP is a request / response protocol. There is no persistent connection between the browser and the server. The code in Session_End thus effectively does nothing — it can't tell the browser to do anything.
You would need to make a (client-side) JavaScript timer and actively load the logout page right before the session timeout elapses.
Session_End in my experience gets called on the first postback (could be implemented via a client-side Timer) after the timeout occurred - whenever that might be... if the user just closes the browser this event may never be called (except for the case you made a specific JS handler unload to do the postback in that situation).
For some information see:
http://justgeeks.blogspot.com/2008/07/aspnet-session-timeouts.html
http://www.highoncoding.com/ArticleDetails.aspx?articleID=108
http://forums.asp.net/t/1271309.aspx/2/10
http://www.codeproject.com/KB/aspnet/PageTracking.aspx
http://p2p.wrox.com/asp-pro-code-clinic/1648-session_onend-not-firing.html
http://aspalliance.com/1182_Troubleshooting_Session_Related_Issues_in_ASPNET.all
This doesn't seem to be the correct way of testing your session timeout. Try putting something in the session variables. Don't touch the page for another couple of minutes, and try reading it back from Session. If your session is alive, you should be able to see the variables, else... you won't.
Learn more about session and troubleshooting session... http://aspalliance.com/1182_Troubleshooting_Session_Related_Issues_in_ASPNET
I came across a weird behavior today w/ my web application. When I navigate from a page to another, I lose one particular session variable data.
I'm able to launch the app in firefox and able to see that the session data is not lost.
I use Response.Redirect(page2, false) to redirect to another page.
Below code was used to track session variables
System.IO.StreamWriter sw = new System.IO.StreamWriter(#"c:\test.txt", true);
for (int i = 0; i < Session.Count; i++)
{
sw.WriteLine(Session.Keys[i] + " " + Session.Contents[i]);
}
sw.Close();
Can anyone help me in this? Any help is appreciated.
I was having exactly the same problem and in my case I found the cause of this behavior. It turned out to be that when I was invoking the Response.Redirect() method I was using the full url instead of just the page name. So when I was in localhost/myapp/page1.aspx I redirected to MYMACHINENAME/myapp/page2.aspx and that's why the sessions were different for each page. I corrected this in my code using only "page2.aspx" and then the final url on any browser (IE, firefox) was localhost/myapp/page2.aspx.Don't know if you're playing with the urls the way I was doing it but maybe this answer can give you a clue. Thanks and good coding
Are you developing in a web farm / web garden environment?
Try using the state server mode. Depending on how your application pool is configured and your deployments the default in-process mode can be unpredictable.
My problem was as follows :-
Problem: When we have moved the ASP.NET application to an another server (Windows Server 2008 R2) with IIS 7.5, the application cannot move session values between the pages. e.g. the session value was set in first page but it could not move to next page. In next page, value for same session variable was coming NULL.
Session values was moving to next page in case of Google Chrome and Firefox but not in Internet Explorer.
Resolution: We have created URL name with "_" (underscore) e.g. http://MySite_test.com. After removing "_", it works as required e.g. http://MySitetest.com
Other Possible Solution:
Use Response.Redirect with having second parameter as "false" to avoid execution of page and thus to avoid lose session token. You have to use URL as follows. Response.Redirect("NextPage.aspx",false)
If the application pool of the site is configured as a web farm or a web garden (by setting the maximum number of worker processes to more than one), and if you're not using the session service or SQL sessions, incoming requests will unpredictably go to one of the worker processes, and if it's not the one the session was created on, it's lost. The solutions to this problem is either not to use a web garden if you don't need the performance boost, or use one of the out of process session providers.
I have a simple ASP.NET MVC application. When the first action method is run it stores some data in the Session variable. On the resulting view I have a jquery ajax call triggered by a button to another action method.
When I click the button a different session id is used at the server side, it's a bit random. There is sometimes a gap of a second or so between starting and clicking the button and the Session ID still changes. This breaks the app as it tries to retrieve the data stored by the first action method.
Any idea what's going on? Both requests are to the same URL.
I see method one instantiate a new session with Id X and store the data.
Immediately after loading the Jquery request fires. I see a different session cookie id on the request header.
I get an error "data not found"
Many thanks,
This is by design and ASP.NET tries to be efficient in storing sessions for users. Remember unless you store anything in session the session value changes.
If you want to tell ASP.NET that you want it to track user sessions, you can do one of 2 things:
Store something in the session.
Simple handle the Session_Start event in your GLobal.asax. The presence of this method will tell ASP.NET to track sessions , even if there is no data in the session..
// NOTE: There is no need to add any thing to session if you are doing this...
public void Session_Start(object sender, EventArgs e)
{
}
This behavior had caused me much worry in the past :)
Are all your AJAX calls using the same server name:
http://localhost/whatever
vs
http://machinename/whatever