如何永久存储cookie

时间:2015-06-09 10:20:15

标签: c# asp.net session cookies web-config

我不想在我的应用程序代码中显示邮件ID。我想给文本框以及我将给它的电子邮件ID应该存储在web.config文件中,直到我更改它。

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>

3 个答案:

答案 0 :(得分:5)

string MailID = ConfigurationManager.AppSettings["MailId"];

创建一个cookie

HttpCookie mailCookie= new HttpCookie("mailCookie");

在Cookie中添加键值

mailCookie.Values.Add("MailID", MailID);

设置Cookie到期日期时间。保持最大值。

mailCookie.Expires = DateTime.MaxValue;

最重要的是,将cookie写入客户端。

Response.Cookies.Add(mailCookie);

从请求中读取cookie。

HttpCookie mailCookie= Request.Cookies["mailCookie"];
if (mailCookie== null)
{
    //No cookie found or cookie expired.
}

找到Cookie。

if (!string.IsNullOrEmpty(mailCookie.Values["MailID"]))
{
    string MailID= mailCookie.Values["MailID"].ToString();
}

答案 1 :(得分:1)

伪代码:

添加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);

按名称读取(获取)Cookie的代码

HttpCookie ck_d = Request.Cookies["d"];
 if(ck_d!=null)
 {
     // logic here
 }

答案 2 :(得分:0)

        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
        }