ASP.NET基礎トレーニング-Cookieの活用

7740 ワード

Cookiesには多くの名前があり、HTTP Cookie、Web Cookie、Browser Cookie、Session Cookieなどがあります.
ウェブサイトの開発の過程で、多くの初心者が実際にそれを乱用した.
その正確な意味は、Webサイトのユーザーの個人データを格納するために使用され、いつ格納されるかということです.
クライアントとサーバが未接続の場合に保存されます.つまり、ローカルのオフラインデータが存在します.
実際、Cookieは、サーバがクライアントにローカルに存在する小規模なテキストを送信することです.
 
シーンを使用:
ユーザ認証、セッション認証、ユーザの好み設定、カートデータ、またはテキストを転送できる他の業務.
Cookieを作成するには:
方法1(HttpCookieクラスを使用):
//First Way
HttpCookie StudentCookies = new HttpCookie("StudentCookies");
StudentCookies.Value = TextBox1.Text;
StudentCookies.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(StudentCookies);

方法2(Responseを直接使用):
//Second Way
Response.Cookies["StudentCookies"].Value = TextBox1.Text;
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);

1つのCookieに複数の値を格納します.
//Writing Multiple values in single cookie
Response.Cookies["StudentCookies"]["RollNumber"] = TextBox1.Text;
Response.Cookies["StudentCookies"]["FirstName"] = "Abhimanyu";
Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar";
Response.Cookies["StudentCookies"]["LastName"] = "Vatsa";
Response.Cookies["StudentCookies"]["TotalMarks"] = "499";
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1); 

Cookieの値を取得するには:
単一の値:
string roll = Request.Cookies["StudentCookies"].Value; 

複数の値:
//For Multiple values in single cookie
string roll;
roll = Request.Cookies["StudentCookies"]["RollNumber"];
roll = roll + " " + Request.Cookies["StudentCookies"]["FirstName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["MiddleName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["LastName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["TotalMarks"];
Label1.Text = roll; 

Cookieを削除するには:
if (Request.Cookies["StudentCookies"] != null)
{
    Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(-1);
    Response.Redirect("Result.aspx");  //to refresh the page
}

 
Now, fish! Can you use the cookie correctly?