Why my session state in MVC4 suddenly loses data? - asp.net-mvc

I was reading in the following page that continualy WindowsAzure recycle store sessions
Why do my instances recycle when trying to store sessions in co-located Azure cache?
This is my webconfig setting:
<sessionState mode="InProc" timeout="2880" />
I was reading that maybe I have to change the Mode to maintain the session alive, because when I'm using the program, suddenly happens that. Let's going to see later than one hour.
What can I do to avoid this bad user experience?

If you are running multiple instances, then you are losing session data as the load balancer bounces users between instances. The "InProc" setting stores the session data on each individual instance and NOT across instances - read more.
If you want to use co-located cache then your config should look something like:
<!-- Windows Azure Caching session state provider -->
<sessionState mode="Custom" customProvider="AFCacheSessionStateProvider">
<providers>
<add name="AFCacheSessionStateProvider"
type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"
cacheName="shared"
dataCacheClientName="shared"
applicationName="AFCacheSessionState"/>
</providers>
</sessionState>
Read more.
UPDATE: Finally, check that you are using a REAL BLOB connection string in your ServiceConfiguration.cscfg file. If the connection string says "UseDevelopmentStorage=true", the deployed role will never be able to create/connect to the cache - it will work locally in the emulator though.:
<Setting name="Microsoft.WindowsAzure.Plugins.Caching.ConfigStoreConnectionString" value="UseDevelopmentStorage=true" />

Related

Session expires very often in MVC application

I am working on developing MVC5 application.
I have used session to store user data.
Below is the code which i am using to store session data
if (Session["UserData"] == null)
{
Session["UserData"] = _objLoginSession;
}
I have also increased Session Timeout in web.config, which is as below
<sessionState mode="InProc" timeout="60">
</sessionState>
My authentication mode is also none
<authentication mode="None" />
But when i run my application, it expires with in 1 - 2 minutes only.
Can anyone please guide me on this?
One reason why ASP.NET session might expire that comes to mind is this: session data is kept in memory since you specified InProc mode, so if you recompile your application in Visual Studio or for some reason your application is restarted you will lose session data. And there are plenty of reasons why your application might get restarted by the web server. Things like changing web.config or some files in the bin folder or your computer starts running on low memory.
All those reasons indicate that you should absolutely never (except while developing) keep session data in memory (InProc).

Cookie expires or session timeout too soon

I have code like this which is run when a user is authorized:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
email,
DateTime.Now,
DateTime.Now.AddMinutes(120),
true,
userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
faCookie.Expires = authTicket.Expiration;
Response.Cookies.Add(faCookie);
I then redirect to a controller/Action that has the Authrize attribute:
[Authorize]
public class ProductsController : Controller
{
I have the following in web.config:
<authentication mode="Forms">
<forms loginUrl="~/Home/Unauthorized" timeout="2880" />
</authentication>
<sessionState timeout="120"></sessionState>
However users are complaining of session timing out or redirecting Home/Unauthorized after a couple of mins of inactivity.
what could be causing this, what else should i check?
A couple of thoughts before I go into a possible solution of why your logins are expiring. First, the FormsAuthentication cookie and SessionState are two different things completely. You can have one or the other, or both or neither. As a result, the timeouts for these two items are also not related.
The FormsAuthentication cookie is an encrypted cookie that contains some basic information such as the user name and an expiration value. The .NET application uses this cookie once a user has authenticated to know if the user is authorized for certain resources.
What controls the encryption and decryption of the FormsAuthentication cookie is the MachineKey for that web application on IIS. The MachineKey is a set of keys used to encrypt and decrypt the cookie. By default, a web application on IIS is set to AutoGenerate the machine key. What this means is that when an application starts, a random machine key is generated. If an application recycles, you get a new machine key. Additionally, if you are hosting on a shared provider, the web host will typically have your application load balanced, meaning hosted by more than one server. Each one of those servers will auto generate a machine key.
If your web application is on a load balanced scenario, then each machine in the web farm cannot decrypt the other's encrypted cookie. This will give the appearance of "being logged out". The example of this is logging in on web server A, then a subsequent request goes to web server B. Web server B does not share a machine key with web server A and cannot decrypt the cookie, sending the user back to the login page.
The solution is to define the MachineKey section in your web.config so each instance of IIS will use the same keys as well as if the application pool recycles, you still have the same machine key.
Here would be an example machine key (use the .NET 2.0 version) that you could place in your web.config
<system.web>
<machineKey validationKey="EBC1EF196CAC273717C9C96D69D8EF314793FCE2DBB98B261D0C7677C8C7760A3483DDE3B631BC42F7B98B4B13EFB17B97A122056862A92B4E7581F15F4B3551"
decryptionKey="5740E6E6A968C76C82BB465275E8C6C9CE08E698CE59A60B0BEB2AA2DA1B9AB3"
validation="SHA1" decryption="AES" />
</system.web>
Additional thoughts are that your expiration in your web.config (2880) and what you are actually setting the expiration to be (120) do not match. You may want them both to match.
If you are running behind a load balancer you will want to ensure that the web farm is using a consistent key as pointed out by Tommy's answer.
Other things to check will be that the IIS metabase settngs for each server are identical. They need to have the same path and ID.
You will also want to look at holding session out of proc (your web.config looks like in proc) which is susceptible to network outage and random app recycles.
Basically a summary of this link.
http://msdn.microsoft.com/en-us/library/vstudio/ms178586(v=vs.100).aspx
If you can post more of your config if possible and give more detail about your environment setup it will be easier to point you in a more focused direction.
Try This one:
web.config Code:
<system.web>
<httpRuntime maxRequestLength="40000000" useFullyQualifiedRedirectUrl="true" executionTimeout="600000" />
<authentication mode="Forms">
<forms loginUrl="~/Home/Unauthorized" timeout="2880" cookieless="UseCookies" />
</authentication>
</system.web>
This will help you.

After adding the SessionState tag in web.config file, URL gets changed.

I am developing MVC application.
I have added the below code in web.config to handle session.
<system.web>
<sessionState mode="InProc" cookieless="true" timeout="30" />
</system.web>
after adding this code , when I run the application , I get the following url in browser.
http://localhost:65344/(S(egpaesodxcoii0dxtczyi10c))/Login/LoginUser
I am confused about (S(egpaesodxcoii0dxtczyi10c)) this part.
if I remove this SessionState tag
<sessionState mode="InProc" cookieless="true" timeout="30" />
from web config then it start appearing normal like below
http://localhost:65344/Login/LoginUser
whats the issue ?
There is no issue.
When you use Cookieless sessionstates, the user's sessionId is embedded in the url. If you do not want this embedded you should consider setting Cookieless to false.
I recommend you have a read of this documentation it should outline the differences between the two.
Hope you find this useful.
There are two ways that session state can store the unique ID that associates the client with a server session: by storing an HTTP cookie on the client or by encoding the session ID in the URL. Storing the session ID in the cookie is more secure but requires the client browser to support cookies.
For applications that allow clients that do not support cookies, such as a variety of mobile devices, the session ID may be stored in the URL. The URL option has several drawbacks. It requires that the links on the site be relative and that the page be redirected at the beginning of the session with new query-string values, and it exposes the session ID right in the query string, where it can be picked up for use in a security attack.
You are encouraged to use the cookieless mode only if you need to support clients that lack cookie support.
So setting : cookieLess to False will work for you
<system.web>
<sessionState mode="InProc" cookieless="false" timeout="30" />
</system.web>

ASP.NET Session Times out more earlier than expected

My current running configuration looks like this
<sessionState mode="InProc" timeout="30" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" protection="All" name="Auth_Cookie" path="/" slidingExpiration="true" timeout="30" />
so I expect it to at least let the user be logged in for half an hour (if he does not make any requests)
but the session time out is hit like after 3-4 minutes if the user is not active. I mean global.asax's Session_End event is hit in this time and then in Application_PostAcquireRequestState event I check if any session variables are null and if they are then I sign the user out and redirect him to the log in page. I cant see what is the problem. Am I misunderstanding how this whole works ? what should I do in order to achieve what I want. Thanks in advance
From your comment:
I am constantly rebuilding the solution. is that be it ? can it be
clearing session variables ?
So basically you are recycling the application pool killing everything stored in the session. The biggest problem with ASP.NET Session is that by default it is stored in-memory:
<sessionState mode="InProc"
This has the drawback that if the application pool is restarted you will lose everything you stored in it. And don't forget that the application pool could be restarted by IIS at any time. For example after some period of inactivity or if some CPU/memory thresholds are reached. Also if you deploy your application in a web farm, InProc session simply won't work because the nodes of your farm cannot share session information.
All those drawbacks are the reasons why I never use ASP.NET Session in my web applications and simply put this in my web.config:
<sessionState mode="Off"

Session ID embedded in URL's is very annonying

I have an ASP.NET 4 site with url's having session string embedded in them. Due to this Google index the same page multiple times, all with different session id's. This is affecting my ranking. Earlier i also had the aspautodetectcookie string appended to the url. But i was able to remove it, however the session id embedded in the url remains a problem still.
If my url is http://www.somesite.com/ViewProduct.aspx?ID=12, it shows up like this http://www.somesite.com/S(yya4h4rf4gjh5eo4uazix2t055)X(1))/ViewProduct.aspx?ID=12. I want it to show like http://www.somesite.com/ViewProduct.aspx?ID=12 all the time.
Here are some settings in my web.config that may help you help me
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="~/AccessDenied.aspx" name="FORMAUTH" />
</authentication>
<sessionState mode="InProc" cookieless="false" timeout="15" />
<anonymousIdentification cookieless="AutoDetect" enabled="false" />
Now one user asked to change cookieless="true" to fix the problem. However in the artcle http://www.beansoftware.com/ASP.NET-Tutorials/Cookieless-Session-State.aspx the guy says that by adding cookieless = "true" session id 'will be' embedded in all page URLs.
Can anyone tell me how remove this session from the url - forever.
I am running on IIS 7 but do not have much access to the admin features.
If you set cookieless="false" that will solve the problem you are seeing with Google.
However this means that any browser, which doesn't support cookies, will get a new session per request. If you want more help, please tell us how you are using the sessions.

Resources