Asp.net Cookie (Çerez) Okuma
Siteniz ile veya kullanıcı ile alakalı bilgileri kaydetmek veya kullanmak için Asp.net ile cookie hazırladınız. Şimdi sıra geldi bu cookie bilgileri nasıl okuyacaksınız ve nasıl kullanacsınız. cookie bilgilerini okumak için Request.Cookies fonksiyonu kullanılır kendisine verilen parametredeki cookileri istenilen değişkenin içine aktarır.
HttpCookie cookie = Request.Cookies["kullanici"];
ile kullanici isimli cookie de saklanan bilgileri cookie isimli değişkene aktarıyoruz bunları kullanabilmek için
string ulke = cookie["ulke"]; string sehir = cookie["sehir"]; string isim = cookie["isim"];
komutlarını kullanabilirsiniz..
Örneğimizdeki kodların tamamı
<%@ Page Language="C#" %> <%@ Import Namespace="System.Net" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Page_Load(object sender, System.EventArgs e) { if (!this.IsPostBack) { HttpCookie kullanicibilgi = new HttpCookie("kullanici"); kullanicibilgi["ulke"] = "Türkiye"; kullanicibilgi["sehir"] = "Amasya"; kullanicibilgi["isim"] = "Bilişim Öğretmeni"; kullanicibilgi.Expires = DateTime.Now.AddDays(7); Response.Cookies.Add(kullanicibilgi); } } protected void Button1_Click(object sender, System.EventArgs e) { HttpCookie cookie = Request.Cookies["kullanici"]; if (cookie != null) { string ulke = cookie["ulke"]; string sehir = cookie["sehir"]; string isim = cookie["isim"]; Label1.Text = "Cookie bulundu bilgileriniz<br/>"; Label1.Text += "İsim: " + isim; Label1.Text += "<br />Ülke: " + ulke; Label1.Text += "<br />Şehir: " + sehir; } } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>asp.net cookie örnekleri: www.aspnetornekleri.com</title> </head> <body> <form id="form1" runat="server"> <div> <h2 style="color:Teal">asp.net Cookie örnekleri: Cookie Okuma</h2> <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="DarkGreen"> </asp:Label> <br /><br /> <asp:Button ID="Button1" runat="server" Text="Cookie Oku" OnClick="Button1_Click" Font-Bold="true" ForeColor="HotPink" /> </div> </form> </body> </html>