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;
Related
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
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>
I am facing a problem,
I have set session time out in web.config
<system.web>
<sessionState timeout="60" mode="InProc" />
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
</system.web>
In my controller
public ActionResult CreateBrand()
{
Session.Timeout=60;
Purchase purchase = Session["purchaseItem"] as Purchase;
if (purchase!=null && purchase.Brand != null)
{
return View(purchase.Brand);
}
return View();
}
You never actually ask a question, so I'll take a stab at guessing what you're asking...
<sessionState timeout="60" mode="InProc" />
When mode="InProc", setting timeout="60" usually does not extend the session timeout beyond 20 minutes because the application pool will spin down (by default) after 20 minutes.
No application pool = no process = no session.
Either change your application pool settings or use a different session state provider.
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
I'm having problem with our login procedure.
Some customers complain that they can't login. I can see in our logs that their login is successful and that they are redirected from the login page to the member area. But there somehow the login isn't detected and they are bounced back to the login page.
I've asked customers to check if cookies are supported (http://www.html-kit.com/tools/cookietester/) but problem remains even if this test returns true.
This is how I've implemented the login procedure (simplyfied):
protected void Login(string email, string password)
{
FormsAuthentication.SignOut();
Guid clientId = /* Validate login by checking email and password, if fails display error otherwise get client id */
FormsAuthentication.SetAuthCookie(clientId.ToString(), true);
HttpContext.Current.Response.Redirect("~/Members.aspx");
}
On the member page I check for authentication by in Page_Load function:
public static void IsAuthenticated()
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
HttpContext.Current.Response.Redirect("~/Login.aspx", true);
}
}
Maybe I'm using FormsAuthentication completely wrong?
I've asked this before but still haven't been able to figure this out, I'd appreciate any help.
From my Web.Config:
<system.web>
<compilation debug="false">
<assemblies>
...
</assemblies>
</compilation>
<authentication mode="Forms"/>
<sessionState mode="InProc" cookieless="false" timeout="180"/>
<customErrors mode="On"/>
<httpHandlers>
...
</httpHandlers>
<httpModules>
...
</httpModules> </system.web>
public static void IsAuthenticated()
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
HttpContext.Current.Response.Redirect("~/Login.aspx", true);
}
}
is not necessary when you use forms authentication.
When you specify the forms authentication in the web.config (in which you also specify the login page)
<authentication mode="Forms">
<forms loginUrl="/Authorization/Login" timeout="60" />
</authentication>
and you deny all non-athenticated users access
<authorization>
<deny users="?" />
</authorization>
you don't have to check the authentication of a user yourself, the framework takes care of that.
I would place the FormsAuthentication.SignOut(); code behind a 'logout' link
Seperate the call of SignOut() and SetAuthCookie() in different methods. You may call FormsAuthentication.SignOut(); when the Login page loads first time - simply just do away from calling SignOut() on Login page. And Call
FormsAuthentication.SetAuthCookie(clientId.ToString(), true); after authentication is successful.
Normally you would use FormsAuthentication.Authenticate together with some membership provider, but this should work, and it actually does in my machine.
Are you removing the FormsAuthentication from your registered HTTP modules? Normally, this is in the machine wide web.config:
<configuration>
<system.web>
<httpModules>
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
</httpModules>
</system.web>
</configuration>
If you put a <clear /> inside that same section of your own web.config, you're effectively removing that module.
My tested Web.config is pretty clean, it only has <authentication mode="Forms"/> configured.