set the timeout for a specific session - c#

How I can set the timeout for a session specific in ASP.NET? it is possible?
I have two or more sesions in my web application, I need set:
Session["foo"] //expire in 14minutes
Session["baa"] //expire in 30minutes
I'm wanting solve this case,if possible not using cookies.
Thanks in advance!

You can configure the timeout for a session in the Web.config file:
<configuration>
<sessionstate mode="inproc"
cookieless="true"
timeout="14" />
</configuration>
This is the default mode (InProc) for ASP.NET. As rockinthesixtring said in his comment, you can't configure the timeout for individual objects in the session, just the session as a whole.
ASP.NET Session State Overview

for specific session
lets say you want to make timeout for this session Session["foo"] =14 min
you can do like this
DateTime timenow=DateTime.now;
DateTime timeafter14min=timenow.AddMinuits(14);
if(DateTime.Now>timeafter14min)
{
HttpContext.Current.Session["foo"]=null;
}
session not expired but cleared

<sessionState
mode="InProc"
stateNetworkTimeout="10" //seconds
cookieless="UseCookies"
cookieName="ASP.NET_SessionId" //Specifies the name of the cookie that stores the session identifier.
timeout="20" //seconds
regenerateExpiredSessionId="true"
useHostingIdentity="true">
</sessionState>
or
session["user"]=textbox_username.txt
<configuration>
<system.web>
<sessionState cookieless="true"
regenerateExpiredSessionId="true" />
</system.web>
</configuration>

Since other questions are being closed as duplicates of this question I would like to add this option here for people who may find it useful.
You can set the Session Timeout manually using the following:
Session.Timeout = 60
You can read more here:
https://msdn.microsoft.com/en-us/library/ms525473(v=vs.90).aspx

Related

How can I set infinity session time out in asp.net project

I'm working on asp.net project. how can I increase the session timeout? (infinity timeout)
Or should I do this on IIS? If it is possible, please explain.
You can set session timeout in web.config as shown below. The value is showing minutes, so you can set as long as you want, up until a year.
<configuration>
<system.web>
<sessionState timeout="200"></sessionState>
</system.web>
</configuration>
The Timeout property can be set in the Web.config file for an
application using the timeout attribute of the sessionState
configuration element, or you can set the Timeout property value
directly using application code.
The Timeout property cannot be set to a value greater than 525,600
minutes (1 year). The default value is 20 minutes.
You cannot assign it to unlimited. You can increase the value in minutes using the time out attribute of Session state element in web.config
<sessionState timeout="30">
</sessionState>
By default session timeout value is 20 minutes. Also in your case if you are using forms authentication, check the authentication time out value as well
<authentication mode="Forms">
<forms loginUrl="logon.aspx" protection="All" path="/" timeout="30" />
</authentication>
one way is by setting the timeout in web.config file. Like
<configuration>
<system.web>
<sessionState mode="InProc" timeout="120"/>
</system.web>
</configuration>
The other way is by setting the time-out in server side code in .cs file. Like
Session.Timeout = 100;
The time-out value entered will be read as minutes. If set to 0, then there will be an error page displaying session time-out value cannot be 0 and must be >0.

Custom OutputCache provider is not working (get is called but not set or add)

In an ASP.NET MVC4 application I have a custom output cache provider defined.
My configuration is like this:
<system.web>
<caching>
<outputCache defaultProvider="DiskOutputCache" enableOutputCache="true" >
<providers>
<add name="DiskOutputCache" type="ProExam.DMC.MvcUtil.DiskOutputCache, ProExam.DMC.MvcUtil, Version=1.0.0.0, Culture=neutral"/>
</providers>
</outputCache>
<outputCacheSettings>
<outputCacheProfiles>
<add name="forever" duration="2147483647" varyByParam="id" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
I have an action like this:
[OutputCache(CacheProfile = "forever")]
public ActionResult View(UrlParamString id)
{
...
}
When I run in debug, only the get method of my custom output cache provider is called. Never the set or the add. Any help would be appreciated...
Try reducing the duration. You defined an almost infinite cache duration this means while the app is running, it will not try to store your cache item again.
Duration is set in seconds... Try duration="10" or something and see what happens.
Apart from that you can also try to define enabled="true" location="Server" in your cache profile.
Try adding location attribute to web.config entry.
<add name="LongLivedProfile" duration="86400" location="Any" varyByParam="*" />
Check that you do not write any cookies during the request. Outputcache does not call add/set if you write a cookie.
Check This: Custom OutputCache provider is not working (get is called but not set or add)
It doesn't work if you are using cookies.
Also Check Note Section for CacheProfile: https://msdn.microsoft.com/en-us/library/vstudio/hdxfb6cy(v=vs.100).aspx
This attribute is not supported for # OutputCache directives included in user controls (.ascx files). When specified on a page, the value must match the names of one of the available entries in the outputCacheProfiles element under the outputCacheSettings section. If the name does not match a profile entry, an exception is thrown.

Session timeout

I have a problem in creating Session. Session.Timeout doesn't work.
This is my code
Session["UID"] = Uid;
Session["UserName"] = UserName;
Session.Timeout = 10; // ?not responding
Session.Timeout occurs after 3 or 4 minutes
You should set session timeout in the web.config file like this:
<sessionState
mode="InProc"
cookieless="AutoDetect"
timeout="10" />
Taken from here: MSDN on the session state element in web.config
try b making changes in your web.config file instead of the cs file.
<configuration>
<system.web>
<sessionState
mode="InProc"
cookieless="true"
timeout="30" />
</system.web>
</configuration>
read more about it at MSDN

SessionManager and Session is null randomly

I have been faced with this problem for months and I have read almost all I can about this and implemented most solutions but still nothing has changed. I don't know where I am making my mistake.
I am using a custom SessionManager class to get/set values into Session easily in my ASP.net CMS websites' admin panels. When the user logins I store user data to the Session then read in Admin.master page to check if the user is logged in. On different servers and also on localhost, the SessionManager.CurrentUser value is null at random times, sometimes 2 minutes sometimes 20 minutes after login, whether the page is idle or not. All my websites have the same problem.
My SessionManager.cs is
public class SessionManager
{
public SessionManager() { }
public static User CurrentUser
{
get { return (User)HttpContext.Current.Session["crntUsr"]; }
set { HttpContext.Current.Session["crntUsr"] = value; }
}
public static string CurrentAdminLanguage
{
get
{
if (HttpContext.Current.Session["crntLang"] == null) HttpContext.Current.Session["crntLang"] = SiteSettings.DefaultLanguage;
return HttpContext.Current.Session["crntLang"].ToString();
}
set
{
HttpContext.Current.Session["crntLang"] = value;
}
}
}
Note: User class is [Serializable]
In Admin.master Page_Load
if (SessionManager.CurrentUser == null) Response.Redirect("../login");
In web.config
<system.web>
<sessionState mode="InProc" customProvider="DefaultSessionProvider" cookieless="UseCookies" regenerateExpiredSessionId="true" timeout="60"/>
<machineKey validationKey="CC0...F80" decryptionKey="8BF...1B5" validation="SHA1" decryption="AES"/>
<authentication mode="Forms">
<forms loginUrl="~/login" timeout="60" slidingExpiration="true" cookieless="UseCookies" />
</authentication>
<system.webServer>
<modules>
<remove name="Session"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
</modules>
I really have no more ideas to solve this issue. Please help :(
Have you checked your application pool recycling timeout? That's a common issue for session "disappearing" prior than expected. Check in IIS
If you have problems, you could set up SQL Server for handling the session, which will persist it if the AppPool is recycled, or the server is rebooted.
For more information: http://support.microsoft.com/kb/317604
Here is a sample web.config code. I don't like the regenerateExpiredSessionId in there and also it is a good practice to have your session timeout to be less than your forms timeout. How ever my advice is to carefully examine your session manager code so you can be sure that you don't reset it somehow. I can think of two thing you could do:
1. Make a test page to check when the session is empty or not and to see if you can at all set a session variable. Try to do a button click (or a ajax request) and set a session variable to keep the session alive every 1 minute or so to see if it expires again even if you keep it alive. If you don't use the Session it will expire. 2. Do some kind of logging. Every time you set a session variable do a DB log of the variable you have set. You could use the test page in 1 to see what exactly you have set in session for the current user.
<authentication mode="Forms">
<forms name="Web-site.ASPXAUTH" loginUrl="~/admin/login.aspx" protection="All" timeout="60" path="/" requireSSL="false" slidingExpiration="true" cookieless="UseDeviceProfile" domain="" enableCrossAppRedirects="false" />
</authentication>
<sessionState timeout="60" mode="InProc" />
<membership defaultProvider="WebSiteMembershipProvider">
<providers>
<clear />
<add name="WebSiteMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="DefaultConnStr" applicationName="web-site" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" requiresQuestionAndAnswer="false" enablePasswordReset="true" enablePasswordRetrieval="false" passwordFormat="Hashed" requiresUniqueEmail="false" />
</providers>
</membership>
<roleManager defaultProvider="WebSiteRoleProvider" enabled="true" cacheRolesInCookie="true" cookieName="Web-Site.ASPXROLES" cookieTimeout="60" cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration="true" cookieProtection="All" createPersistentCookie="false" maxCachedResults="25">
<providers>
<clear />
<add name="WebSiteRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="DefaultConnStr" applicationName="web-site" />
</providers>
</roleManager>

Session timeout on a asp.net with master pages

I have an asp.net app with master pages. I need to have a session timeout after 10 minutes, for which I have a javascript code block. Is there any other more efficient way to do a session timeout rather than have a javascript code block on every page? (I am not using membership provider).
You can change the timeout of your session in your web.config
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
stateNetworkTimeout="10"
sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI"
sqlCommandTimeout="30"
customProvider=""
cookieless="UseCookies"
cookieName="ASP.NET_SessionId"
timeout="10"
allowCustomSqlDatabase="false"
regenerateExpiredSessionId="true"
partitionResolverType=""
useHostingIdentity="true">
<providers>
<clear />
</providers>
</sessionState>
reference:http://msdn.microsoft.com/en-us/library/h6bb9cz9(vs.80).aspx
you can simply do this on server side. there is no point to time your session on client side. in that case, you can do it centrally on master page or webconfig or global.asax.
Using javascript is a bad idea, you can do what you want easily on the server.
Add this to your Global.asax
protected void Session_Start(object sender, EventArgs e)
{
Session.Timeout = 10;
}
And this to your web.config
<configuration>
<system.web>
<sessionState timeout="10"></sessionState>
</system.web>
</configuration>
You need to add both to make it work effectively.
You can made changes in web.config file by adding following to have session timeout:
<system.web>
<authentication mode="Forms">
<forms timeout="10"/>
</authentication>
<sessionState timeout="10" />
</system.web>
You can do it from c# by using following code:
Session.Timeout = 10;

Categories

Resources