Cookie is not stored after refresh .net mvc - c#

I am testing something quick, but I can't save cookies into browser. When I check cookies in browser they are not there. My code:
private void WriteCookie(string setting, string settingValue)
{
HttpCookie myCookie = new HttpCookie(setting);
// Set the cookie value.
myCookie.Value = settingValue;
// Set the cookie expiration date.
myCookie.Expires = DateTime.Now.AddDays(10);
// Add the cookie.
Response.Cookies.Add(myCookie);
}
private string ReadCookie(string setting)
{
HttpCookie myCookie = new HttpCookie(setting);
myCookie = Request.Cookies[setting];
// Read the cookie information and display it.
if (myCookie != null)
return myCookie.Value;
return null;
}
I am setting cookie in MVC action #1:
if(page != null)
{
WriteCookie("page", page.ToString());
}
if (pageDraft != null)
{
WriteCookie("pageDraft", pageDraft.ToString());
}
Then I read:
if (ReadCookie("page") != null)
page = Convert.ToInt32(ReadCookie("page"));
if (ReadCookie("pageDraft") != null)
pageDraft = Convert.ToInt32(ReadCookie("pageDraft"));
When page is refreshed, I lose cookies. Why?

Probslem was web.config:
<httpCookies requireSSL="true" />
Changed to:
<httpCookies httpOnlyCookies="true" requireSSL="false" />

Related

How to remember a Session if the user has visited the 'splash/landing' page

I have this really simple C# to redirect users to a splash page when they enter the /default.aspx homepage:
if (Session["homepageHoarding"] == null)
{
Response.Redirect("/homepage-hoardings/limited-offer.aspx");
}
On that 'splash' page: /homepage-hoardings/limited-offer.aspx, there is a link to return to the 'normal' homepage, which of course is: /default.aspx
But it redirects again, thinking that the session doesn't exist, which it doesn't.
How do I get it so that once they've seen the Splash page it remembers that they've seen it? I can't use a global because my terrible web-hosts don't allow it :-(
Many thanks :-)
As said in the comments, use cookies:
bool userVisited = false;
HttpCookie cookie = Request.Cookies["MyCookie"];
if (cookie == null)
{
cookie = new HttpCookie("MyCookie");
cookie.Values.Add("userVisitedSplash", true);
cookie.Expires = DateTime.Now.AddDays(30); //<-- Sets the expiration date
cookie.HttpOnly = true;
this.Page.Response.AppendCookie(cookie);
} else{
userVisited = cookie.Values["userVisitedSplash"]
}
if(userVisited){
Response.Redirect("~/Default.aspx");
} else{
Response.Redirect("/homepage-hoardings/limited-offer.aspx");
}

How to store cookie permanently

I don't want to show mail id in my application code. I want to give text box and what ever email id I will give it should be stored in web.config file for ever until I change it.
string store= "kumar#gmail.com";
ConfigurationManager.AppSettings["MailId"] = store;
string message1 = ConfigurationManager.AppSettings["MailId"];
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="2001"/>
<add key="MailId" value="krishnamohan.p#sun.com" />
</appSettings>
string MailID = ConfigurationManager.AppSettings["MailId"];
Create a cookie
HttpCookie mailCookie= new HttpCookie("mailCookie");
Add key-values in the cookie
mailCookie.Values.Add("MailID", MailID);
set cookie expiry date-time. Keep it max value.
mailCookie.Expires = DateTime.MaxValue;
Most important, write the cookie to client.
Response.Cookies.Add(mailCookie);
Read the cookie from Request.
HttpCookie mailCookie= Request.Cookies["mailCookie"];
if (mailCookie== null)
{
//No cookie found or cookie expired.
}
Cookie is found.
if (!string.IsNullOrEmpty(mailCookie.Values["MailID"]))
{
string MailID= mailCookie.Values["MailID"].ToString();
}
pseudo code:
Code to ADD cookie
HttpCookie e = new HttpCookie("d");
e.Value = "set-Email-Id";
e.Expires = DateTime.Now.AddDays(30); // expires after 30 days
HttpContext.Current.Response.Cookies.Add(e);
Code to Read ( get ) cookie by it name
HttpCookie ck_d = Request.Cookies["d"];
if(ck_d!=null)
{
// logic here
}
HttpCookie Cookie = new HttpCookie("cksunlightitmailid");
Cookie.Value = txtSunlightitmailid.Text.Trim();
Cookie.Expires = DateTime.MaxValue; // never expire
HttpContext.Current.Response.Cookies.Add(Cookie);
HttpCookie ck_d = Request.Cookies["cksunlightitmailid"];
if (Request.Cookies["cksunlightitmailid"] != null)
{
lblSunlightitmailid.Text = "Ur current email id :" + Request.Cookies["cksunlightitmailid"].Value;
//Or Write ur own code here
}

Not updating cookie values

In my project, I have written code for creating a cookie.
I need to retrieve its value on another page. Here's what I've tried, on the Login.aspx button click event:
Guid guid_string_Id = System.Guid.NewGuid();
string newID = guid_string_Id.ToString();
Response.Cookies["name"]["Font"] = newID;
Response.Redirect("page2.aspx");
On page load for page2.aspx,
if (Request.Cookies["name"] != null)
{
string new_ID;
if (Request.Cookies["name"]["Font"] != null)
{
new_ID = Request.Cookies["name"]["Font"];
}
}
else
{
Response.Redirect("Login.aspx");
}
I always find that cookies value remains same .what will be the problem?
In my web.config, I have set:
<sessionState mode="InProc" regenerateExpiredSessionId="true" stateNetworkTimeout="30" sqlCommandTimeout="30" cookieless="false" timeout="30">
</sessionState>
On your Login.aspx page you just need to add a cookie to the cookies collection:
Guid guid_string_Id = System.Guid.NewGuid();
string newID = guid_string_Id.ToString();
var cookie = new HttpCookie("font", newID);
Response.Cookies.Add(cookie);
Response.Redirect("page2.aspx");

"Remember me" functionality in a Login form

I am using linq to entity connection. I want to keep user logged in once he entered into his account, This is my code. It's not working. Help, please
if (this.ChkRememberme != null && this.ChkRememberme.Checked == true)
{
HttpCookie cookie = new HttpCookie(TxtUserName.Text, TxtPassword.Text);
cookie.Expires.AddYears(1);
Response.Cookies.Add(cookie);
}
if (this.ChkRememberme != null && this.ChkRememberme.Checked == true)
{
int timeout = rememberMe ? 525600 : 30; // Timeout in minutes, 525600 = 365 days.
var ticket = new FormsAuthenticationTicket(TxtUserName.Text, TxtPassword.Text);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);// Not my line
cookie.HttpOnly = true; // cookie not available in javascript.
Response.Cookies.Add(cookie);
}
Go to your web.config and find the authentication element. You can set the cookie expiration time (in minutes) there, like such:
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login"
name="myCookie" <!-- optional, if you want to rename it -->
timeout="2880" /> <!-- expires in 48 hours -->
</authentication>
</system.web>
Source: how to apply "Remember Me" in c#
Hope this helps
Happy Coding..!!
I recommend to use MembershipReboot for authentication purposes in your app (samples are included).

Read cookie to login automatic

I store the cookies when someone is logging in, as below:
List<User> listUser;
//returns 1 user
foreach(User u in listUser)
{
HttpCookie cookieNickname = new HttpCookie("UserNickname");
cookieNickname.Value = u.Nickname.ToString();
cookieNickname.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookieNickname);
HttpCookie cookiePassword = new HttpCookie("UserPassword");
cookiePassword.Value = u.Password;
cookiePassword.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookiePassword);
}
When someone visits the site again, I want to read data from the database which is associated with usernickname-cookie and userpassword-cookie.
Then I want to show the firstname and lastname on a label.
This is what I tried:
List<User> cookieLoggedInUser;
if (Request.Cookies["UserNickname"] != null && Request.Cookies["UserPassword"] != null)
{
//returns 1 user
cookieLoggedInUser = Database.SignIn(Request.Cookies["UserNickname"].ToString(), Request.Cookies["UserPassword"].ToString());
if (cookieLoggedInUser.Count > 0)
{
foreach (User u in cookieLoggedInUser)
{
lblFirstName.Text = u.FirstName;
lblLastName.Text = u.LastName;
}
}
}
But both of the Request.Cookies return null.
Why is that happening?
I wouldn't recommend the approach you took other then for experimeting purposes as it has big security risk.
To make your curent solution work check that you are creating cookies in the same domain where you consume them.
If it is not the case, browser will not send cookies to the other domain.
You can make the sign-in cookie permanent using a technique like this:
protected void Login1_OnLoggedIn(object sender, EventArgs e)
{
CheckBox Remember = (CheckBox)((Login)sender).FindControl("Remember");
if (Remember.Checked)
{
FormsAuthenticationTicket t = new FormsAuthenticationTicket(2, Login1.UserName, DateTime.Now, DateTime.Now.AddYears(5), true, "");
string data = FormsAuthentication.Encrypt(t);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, data);
authCookie.HttpOnly = true;
authCookie.Domain = "";
authCookie.Expires = t.Expiration;
Response.Cookies.Remove("FORMAUTH");
Response.Cookies.Add(authCookie);
Response.Redirect(Request.QueryString["ReturnUrl"]);
}
}
This assumes the site is using asp.net membership services.
The line that says Response.Cookies.Remove("FORMAUTH"); should match the cookie name you have set up in your web.config under this section:
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="~/Login.aspx" name="FORMAUTH"/>
</authentication>
Wire this up to the OnLoggedIn event of your <asp:Login> control and when the user clicks Remember Me they stay logged in.
This is a lot safer than the alternative which you propose (storing unencrypted passwords in cookies).

Categories