Session lost after login - c#

On my website
Filling form before login save data in Session
Login Using Linkedin ID
after login at Pageload taking data from session then inserting into SQL data base
My problem is some times I am getting session and other times I am not getting session (Session Lost) ( mostly when 3-4 people testing at the same time... 2-3 get session and 1-2 not getting session)
Can any one tell me what is the problem? How can I solve this problem?
Any another way to do this task?
Stroing in session before login
Session["sesObjFundRaiseSeek"] = objFundRaiseSeek;
Getting after login
if (Session["sesObjSellSeekBL"] != null)
{
clsSellSeekBL ObjSellSeekBL = (clsSellSeekBL)Session["sesObjSellSeekBL"];
}

Is it a problem with your sessions timing out after a very short period of time? You can input the default session timeout within the web.config. This is done right under system.web. Here is an example where 480 is the number of minutes:
<sessionState timeout="480"></sessionState>
For more information: http://msdn.microsoft.com/en-us/library/h6bb9cz9(v=vs.71).aspx
An alternate solution is to use Cookies. I would recommend using Cookies to store user state information. Since Cookies are stored on the users computer, it is easier to configure:
I set to expiration date to 100000 days later in the example below:
HttpCookie myCookie = new HttpCookie("sesObjSellSeekBL");
myCookie.Value = Convert.ToString(user_id); //store the user id here at the very least
myCookie.Expires = DateTime.Now.AddDays(100000d);
Response.Cookies.Add(myCookie);
Here is how you check your Cookie:
if (Request.Cookies["sesObjSellSeekBL"] != null)
Here is how you log the user out:
HttpCookie myCookie = new HttpCookie("sesObjSellSeekBL");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);

Related

How do I set cookie expiration to session in C#

I am creating a website, and I'm not sure how to use sessions with cookies.
When sessions timeout, I want to show the username and time of the user; for e.g., username stored in cookies and session. When sessions timeout the username must be retrived from the cookies.
Lets put things in perspective first.
A session is the session a user is experiencing when he is using the website.
How it works is basically a user starts a session with the web server, the web server then gives it a key of the session and sets a timeout for the session which are stored as a cookie.
Since this process is automatic and you can only configure it in web.config (unless you are asp.net core vNext, which I doubt) with sessionState https://msdn.microsoft.com/en-us/library/h6bb9cz9%28v=vs.80%29.aspx
A normal HttpCookie on another hand is something you set on your Response object and can give it a specific expiration date like this:
HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);
// Add the cookie.
Response.Cookies.Add(myCookie);
Which suits your needs more likely.
If you want more information about sessions expiration I'd also suggest you check out http://www.hanselman.com/blog/TroubleshootingExpiredASPNETSessionStateAndYourOptions.aspx

Cookies and Sessions Expiration in .NET

I have an MVC4 single application page. In the log-in page there are 3 fields: user, password and "remember me" checkbox.
The C# login code is this:
if (WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return Json(new { success = true, redirect = returnUrl });
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
I want to do this:
If a user logs in with "remember me" true - The cookie will stay until the user logs off.
If the user logs in with "remember me" false - The cookie will expire after 3 hours.
In web.config I have this code:
<authentication mode="Forms">
<forms loginUrl="~/" timeout="180" cookieless="UseCookies" slidingExpiration="false" />
</authentication>
<sessionState timeout="180" />
The problem is when the user doesn't touch the page for a short time (10-30 mins usually), and then the user tries to do something in the page - there is an error
"Authorization has been denied for this request."
(Although sessionStation is more than 30 minutes!)
After the user refresh the page - if the cookie hasn't expired yet - everything works fine. But of course I don't want to make the user refresh the page every 15 minutes or so, it's a single-page-application.
So, I tried to change slidingExpiration to "true" and create a ping (with ajax) every 17 minutes and it really stopped the session expiration and the annoying message - but the cookie didn't expired after 3 hours (I logged in with remember me 'false')!
What can I do?
Right click your application pool from IIS management console and look for "Idle time-out(minutes)".
You can adjust the setting to 0 (zero) which effectively disables the timeout so that the application pool will never shut down due to being idle.
I would double check your IIS settings. See what your App Pool Idle Timeout value is set to. By default it's 20 minutes. When the App Pool goes idle (no users accessing the app pool) for twenty minutes, you will loose session state (All data stored in the session will be cleared).
With more users this problem would work itself out, but presuming you are the only person testing, increasing this value to something greater than 180 minutes will prevent the timeout, or you could set the value to zero to disable the app pool idle timeout altogether.
See this answer for information on checking your app pool timeout in IIS Express... https://stackoverflow.com/a/10222419/386856
Do note that a dead app pool can take several seconds to re-spawn. It may be beneficial to increase this value anyways. This will prevent users from having an extremely slow experience if they happen to be the person that's unlucky enough to have to wait for the app pool to restart.
Update
To allow for a change in timeout for users who don't click remember me, you can create a custom attribute or you could modify the FormsAuthentication timeout via C#. Here are good references on setting the timeout via code. https://msdn.microsoft.com/en-us/library/system.web.configuration.formsauthenticationconfiguration.timeout%28v=vs.110%29.aspx and https://msdn.microsoft.com/en-us/library/system.web.configuration.formsauthenticationconfiguration(v=vs.110).aspx If you want the timeout to expire right at 3 hours, even if the user has activity be sure slidingExpiration is false in your web config. If you want the timeout to expire 3 hours after the user's last activity be sure slidingExpiration is true. So before you set the cookie try something like the following (Be sure to check the OpenWebConfiguration path):
System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/aspnetTest");
AuthenticationSection authenticationSection = (AuthenticationSection)configuration.GetSection("system.web/authentication");
FormsAuthenticationConfiguration formsAuthentication = authenticationSection.Forms;
formsAuthentication.Timeout = System.TimeSpan.FromHours(3);
formsAuthentication.SlidingExpiration = true;
I solved this by just creating my own encrypted cookie which will persist the user's session if present. In an action filter attribute, check if the user's session is expired, check for this cookie. If the cookie exists, verify the information and reestablish the session. If the user doesn't have a session, doesn't have a cookie, or the encrypted credentials are incorrect, redirect the user to the login page. Since everything is handled in the code, there is no guess work on the server settings.
On login with remember me checked:
if (RememberMe ?? false)
{
var authCookie = new HttpCookie(Config.AuthorizationCookie);
authCookie.Values.Add("ID", Crypto.EncryptStringAES(UserSession.Current.Account.ID.ToString(), Config.SharedSecret));
authCookie.Expires = DateTime.Now.AddDays(30);
AuthorizationCookie = authCookie;
}
Response.AppendCookie(AuthorizationCookie);
On page visit without session (done inside an attribute attached to necessary controllers and actions):
_account = UserSession.Current.Account;
// check if there is currently an account in the session
if(_account == null)
{
// check the user authorization cookie for a user id
HttpCookie authCookie = HttpContext.Current.Request.Cookies[Config.AuthorizationCookie] ?? new HttpCookie(Config.AuthorizationCookie);
if (authCookie.HasKeys && !String.IsNullOrEmpty(authCookie["ID"]))
{
// decrypt the user id for database lookup
_userID = Crypto.DecryptStringAES(authCookie.Values["ID"], Config.SharedSecret);
}
}
Re-establish the session if necessary (done inside a database connection)
// called within a database connection's using statement
protected override void Query(DatabaseContext db)
{
// check the database for the user account
if(_account == null && !String.IsNullOrEmpty(_userID))
{
int tempID;
int? id;
id = int.TryParse(_userID, out tempID) ? tempID : (int?)null;
if(id.HasValue)
{
_sessionRestored = true;
_account = db.User.Find(id);
if(_account != null)
{
_account.LastLogon = DateTime.UtcNow;
db.SaveChanges();
}
}
}
}
Finally restore the session:
if (_account != null)
{
// set the current account
UserSession.Current.Account = _account;
if(_sessionRestored)
{
UserSession.Current.Refresh();
}
}
Your code may look a bit different but that is the crux of how I did it.

Problems erasing HTTP Cookie

I have a cookie which stores user info like username, companID etc.
I need to be able to update the cookie if the user logs off and back on using a different account.
The problem I have is that I can't get rid of the previous details. I am expiring the cookie and then trying to give it a new company ID which it will then use to collect the user details but it won't overwrite it.
if (Request.Cookies["UserInfo"] != null)
{
HttpCookie myCookie = new HttpCookie("UserInfo");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
UserInfo.Values.Add("CompanyID", Convert.ToString(ds.Tables[0].Rows[0]["ID"]));
Response.Cookies.Add(UserInfo);
Now after this the cookie still stored the old details with old company ID.

Cookies don't persist after refresh

I am using c# and mvc. I am trying to write a cookie to the user browser. But after a refresh of the browser the cookie disappears.
This is my code for writing the cookie:
movieCookie = new HttpCookie(cookieName);
movieCookie.Value = "test;
movieCookie.Expires = DateTime.Now.AddDays(30);
//add the cookie
HttpContext.Current.Response.Cookies.Add(movieCookie);
and the one for reading the cookie:
//check if such cookie exist
HttpCookie movieCookie = null;
if (HttpContext.Current.Request.Cookies.AllKeys.Contains(cookieName))
movieCookie = HttpContext.Current.Request.Cookies[cookieName];
Another thing to add is that when I searched "AllKeys" like so:
HttpContext.Current.Request.Cookies.AllKeys
it shows an empty string array, for some reason.
any ideas?
Some possibly silly questions
Check your web-servers time and date, are they set correctly, if they are (in your case) 2 years out it will expire cookies immediately.
Check that cookieName is the same
Check that after setting the cookie to the response your not redirecting before the cookie is set. For a cookie to be set you need to set headers and push them out.
I solved it. It appears that in MVC the "return view" after the cookie creation, cause the cookie not to be saved.

Cookie is not getting deleted in IE 8

I'm trying to delete a cookie but somehow it is not getting deleted in IE 8
This is the code i'm using
HttpCookie userCookie = Request.Cookies[cookieName];
if (userCookie != null)
{
userCookie.Expires = DateTime.Now.AddDays(-1);
if (!string.IsNullOrEmpty(cookieDomain))
userCookie.Domain = cookieDomain;
Response.Cookies.Add(userCookie);
}
It is working fine in firfox and chrome .
Suppose the name of the cookie is testcookie. We created this cookie from xyz.com and we set the domain of the cookie as ".xyz.com". Now we are deleting or expiring this cookie from subdomain.xyz.com. We are deleting the cookie with the code we have mentioned above.
Check your cookies. You may have two cookies called "testcookie" or whatever. This has happened to me before and caused a lot of pain. You can check quickly by typing javascript:alert(document.cookie) into the address bar.
If you have got duplicate cookies delete all your cookies and start testing again. I.e. setting your testcookie, then on another request try expiring it again how you were before.

Categories