C# MVC Cookie İle Oturum Açma İşlemleri
C# MVC Cookie İle Oturum Açma İşlemleri için ön görülen kodlama yapısı aşağıdaki gibidir. Sizde projelerinizde kullanabilirsiniz.
Sınıfımızı Oluşturuyoruz
public class MyCookies { public void CreateCookie(string Name, string Value, int TimeMin) { // Cookie anahtarı ile değerini belirlemiş oluyoruz HttpCookie cookieVisitor = new HttpCookie(Name, Value); // Dakika cinsinden (isteğe bağlı değişebilir.[Gün,Ay,Yıl]) değerini belirtiyoruz. cookieVisitor.Expires = DateTime.Now.AddMinutes(TimeMin); // Kaydediyoruz. HttpContext.Current.Response.Cookies.Add(cookieVisitor); } public string GetCookie(string name) { // Böyle bir cookie mevcut mu kontrol ediyoruz if (HttpContext.Current.Request.Cookies.AllKeys.Contains(name)) { // böyle bir cookie varsa bize geri değeri döndürsün return HttpContext.Current.Request.Cookies[name].Value; } return null; } public void DeleteCookie(string name) { // Böyle bir cookie var mı kontrol ediyoruz if (GetCookie(name) != null) { //Varsa cookiemizi temizliyoruz HttpContext.Current.Response.Cookies.Remove(name); // ya da HttpContext.Current.Response.Cookies[name].Expires = DateTime.Now.AddDays(-1); } } }
Controller İçerisinde Atama Yapımı
public ActionResult Index() { MyCookies mc = new MyCookies(); mc.CreateCookie("Ad","Hüseyinn",60); mc.CreateCookie("Soyad","DEMİRDÖĞER",60); return View(); }
CSHTML İçerisinde Çağırma İşlemleri
<h2>@Request.Cookies["Ad"].Value</h2> <h2>@Request.Cookies["Soyad"].Value</h2>