HttpCookie vs Response.Cookie



各位开发人员好,

我对在ASP中使用cookie有点陌生。如果这是一个基本问题,我很抱歉。所以我有以下代码在我的网页。配置,我有点玩弄,以了解cookie。

  <httpCookies httpOnlyCookies="true" requireSSL="true"/>

现在我的问题是。我用两种方法创建了一个cookie(我需要保护它们)。

我保护它的一种方法是使用以下代码-

 protected void btnSubmit_Click(object sender, EventArgs e)
    {
        HttpCookie cookie = new HttpCookie("UserInfo");
        cookie.Secure = true; // secure the cookie
        cookie["username"] = txtEmail.Text;
        if (txtEmail.Text != "")
        {
            Response.Cookies.Add(cookie);
        }
        Response.Redirect("WebForm2.aspx");
    }

现在,当我使用这段代码来创建它时,我得到了UserInfo cookie以这种方式被保护得很好。

protected void btnSubmit_Click(object sender, EventArgs e)
{
     Response.Cookies["UserInfo"]["userName"] = txtEmail.Text;
}

现在我的问题是。为什么使用"响应。"Cookies"默认使用web.config?为什么当我使用HttpCookie创建一个cookie时,我必须通过在CS代码中将其设置为true来保护它?我最好的猜测是,因为我正在创建一个HttpCookie的实例,这就是为什么,但我想进一步的方向。

多谢!

为什么使用"Response。"Cookies"默认使用. config吗?

简单/直接的答案是这是由设计的。

当你调用

时假设cookie不存在
Response.Cookies["UserInfo"]["userName"] = txtEmail.Text;

为您创建cookie并分配值,但给出您在:

中指定的默认值:
<httpCookies httpOnlyCookies="true" requireSSL="true"/>

但是,如果您要像您已经指出的那样实例化并将其添加到集合中,它将使用那些手动设置的值,在new HttpCookie的情况下,Secure属性默认值为false;

在Cookies Collection文档中指定

你可以更近距离地了解HttpCookieCollection的代码,以了解更多的"为什么"。

最新更新