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
}
Related
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" />
I have seen the persistent cookies examples in ASP.NET MVC C# here on stackoverflow.
But I can't figure out why the code below isn't working.
First I write to the cookie:
HttpCookie cookie = new HttpCookie("AdminPrintModule");
cookie.Expires = DateTime.Now.AddMonths(36);
cookie.Values.Add("PrinterSetting1", Request.QueryString["Printer1"]);
cookie.Values.Add("PrinterSetting2", Request.QueryString["Printer2"]);
cookie.Values.Add("PrinterSetting3", Request.QueryString["Printer3"]);
Response.Cookies.Add(cookie);
I see the cookies stored in Internet Explorer. The content looks OK.
Then the reading code:
HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie.Values["PrinterSetting2"].ToString();
The cookie variable keeps null . Storing the PrinterSetting2 value in the test variable fails.
I don't know what I'm doing wrong because this is more or less a copy-paste from the examples here on stackoverflow. Why can't I read the PrinterSetting2 value from the cookie ?
try with below code :-
if (Request.Cookies["AdminPrintModule"] != null)
{
HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie["PrinterSetting2"].ToString();
}
Have a look at this document http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/ :-
Below are few types to write and read cookies :-
Non-Persist Cookie - A cookie has expired time Which is called as
Non-Persist Cookie
How to create a cookie? Its really easy to create a cookie in the
Asp.Net with help of Response object or HttpCookie
Example 1:
HttpCookie userInfo = new HttpCookie("userInfo");
userInfo["UserName"] = "Annathurai";
userInfo["UserColor"] = "Black";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);
Example 2:
Response.Cookies["userName"].Value = "Annathurai";
Response.Cookies["userColor"].Value = "Black";
How to retrieve from cookie?
Its easy way to retrieve cookie value form cookes by help of Request
object. Example 1:
string User_Name = string.Empty;
string User_Color = string.Empty;
User_Name = Request.Cookies["userName"].Value;
User_Color = Request.Cookies["userColor"].Value;
Example 2:
string User_name = string.Empty;
string User_color = string.Empty;
HttpCookie reqCookies = Request.Cookies["userInfo"];
if (reqCookies != null)
{
User_name = reqCookies["UserName"].ToString();
User_color = reqCookies["UserColor"].ToString();
}
You must ensure that you have values in Request.QueryString.Just to check if your code works hard code values of cookies and then read from cookie.
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).
I am using cookies for my website.
I need to remove cookies immediately from browser for that i use this Code in C#
Code for removal of cookie
Response.Cookies["OptDepth"].Expires = DateTime.Now.AddYears(-30);
after execution of this code if i use this code
Code to check value of deleted cookie
Request.Cookies["OptDepth"].value;
then it gives me the value of specified cookie.
I need to remove cookies immediately from browser.
How can i do this.
If we change the name of that cookie with null then it works.
Code
Request.Cookies["OptDepth"].Name = null;
Now problem is solved.
Use Simple Code to replace cookies with expiry date:
if (Request.Cookies["OptDepth"] != null)
{
HttpCookie myCookie = new HttpCookie("OptDepth");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Here is an msdn detail link.Cookies
When adding a cookie ;
HttpCookie cookie = new HttpCookie("try");
cookie.Values["foo"] = "foo";
DateTime date = DateTime.Now.AddSeconds(-30);
cookie.Expires = date;
Response.Cookies.Add(cookie);
When Reading the cookie;
HttpCookie cookie = Request.Cookies["try"];
You will see the cookie is null.
I have a problem with creating HttpOnly Cookies , I use the following code to creat new cookie:
//A.aspx
HttpCookie ht = new HttpCookie("www");
ht.Value = "www";
ht.Name = "www";
ht.HttpOnly = true;
ht.Expires = DateTime.Now.AddDays(1);
Response.AppendCookie(ht);
Response.Redirect("B.aspx");
//B.aspx
HttpCookie cookie = Request.Cookies["Allowed"];
HttpCookie htt = Request.Cookies["www"];
if (cookie != null)
{
Response.Write(cookie.HttpOnly);
Response.Write(htt.HttpOnly);
}
else
{
cookie = new HttpCookie("Allowed");
cookie.HttpOnly = true;
cookie.Value = "ping";
cookie.Expires = DateTime.Now.AddMinutes(2);
Response.Cookies.Add(cookie);
Response.Write(cookie.HttpOnly);
Response.Write(htt.HttpOnly);
}
The problem is that the final result is always : False, although the HttpOnly property is set to True .
Can anyone explain me a way to figure this out ?
Thanx
Cookie parameters (expiration date, path, HttpOnly etc) are not sent back to the server by the browser, only the values. Sending them back would only introduce unnecessary bloat. Therefore the cookies in Request.Cookies will only contain the names and values.
If you want to see if your HttpOnly value is taking effect, use Firecookie or something similar to inspect the cookies. Or try accessing them in JavaScript - that's what it's supposed to prevent.