MVC Durum Yönetimi - MVC Session

Session Kullanımı  


Sunucu tarafında siteye bağlanan her bir kullanıcı için oluşturulan  hafıza bölgesidir.
Session kullanıcı bazlı oluşur. Sayfalar arası gezinirken veri kaybetmemek saklamak için bilgiler sessionda saklanır. Her kullanıcı için session farklıdır.Kullanıcı adını saklamak için sessiona değer atayıp gezinirken kullanıcıya tekrar ulaşabiliriz.
Sunucu makinanın RAM ınde her kullanıcı için farklı oluşur. Session bir objedir. 20 dk işlem yapılmazsa veya tarayıcı kapatılırsa session kapanır.

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string userName)
        {
            Session["UserName"] = userName;
            return RedirectToAction("Index2");
        }

        public ActionResult Index2()
        {
            if (Session["UserName"] !=null)
            {
                ViewBag.Deger = Session["UserName"].ToString();
            }
            else
            {
                ViewBag.Deger = "Session Yoktur";
            }
         
            return View();
        }
        public ActionResult Index3(string text)
        {
            // Session.Clear();  Tüm Sessionları temizle

            if (Session["UserName"] !=null)
            {
                Session.Remove("deger");  // Belirli Sessiondaki değeri silmek için
            }
            return View();
        }


Session süresi default 20 dk dır bunu arttırmak için
Web.config içerisinde system.web tagları arasına

<sessionState timeout="30"> </sessionState>  <!-- Dk cinsinden session temizleme süresi --> 

konutu yazılarak session varsayılan süresini uzatabiliriz.



ApplicationState


Her kullanıcı aynı değişkene anahtar kelimeye ulaşır. Kullanıcıya özgü bir durum değildir. Application değer anahtarına bir değer yazıldığında tüm kullanıcılar global işlem görür . Aynı şeyi okuyup aynı şeyi yazarlar.

        public ActionResult Index()
        {         
            HttpContext.Application["sayac"] = "1";
            //HttpContext.Application.Add("sayac", 1);
            return View();
        }
        public ActionResult Index2()
        {
            ViewBag.Sayac= HttpContext.Application["sayac"].ToString();
            return View();
        }
        public ActionResult Index3()
        {
            int sayac = (int)HttpContext.Application["sayac"];
            sayac++;  //Application["sayac"] değeri 1 artar
            HttpContext.Application["sayac"] = sayac;

            return View();
        }
        public ActionResult Index4()
        {
            HttpContext.Application.Clear(); // Tüm Applicationları siler
            HttpContext.Application.RemoveAll();

            HttpContext.Application.Remove("sayac"); //  sadece Application["sayac"]  siler
            return View();
        }




Cache State

ApplicationState gibidir.Tüm kullanıcılar için Global dir yani tüm kullanıcılar için aynıdır.  .Name value tipiyle çalışır. Ömrü vardır şu tarihte ölsün, son erişimden sonra bu kadar süre sonra ölsün diyebiliriz.

.cs

public ActionResult Index()
{
            HttpContext.Cache.Add("ad","Oktay ALTAN",null,System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0,0,10),System.Web.Caching.CacheItemPriority.Normal,null); // son erişimimden 10 sn sonra temizlenecek
         
            return RedirectToAction("Index2");
        }
        public ActionResult Index2()
        {
            return View();
        }

.cshtml

<div class="row">
    @if (HttpContext.Current.Cache["ad"] !=null)
    {
        var ad = HttpContext.Current.Cache["ad"].ToString();
        <span>@ad</span>
    }
    else
    {
            <span>Cache item "ad" is removed</span>
    }
</div>


Index te oluşan cache Index 2 ye yönlendirildikten  10 sn sonra ömrü sonlanır. Index 2 yi yenilerseniz göreceksinizdir.

Cookie

Bilgisayar bazlı tutuluyor. Şifre gibi bilgileri burada tutmamamız gerekiyor. Kullanım şeklinde anahtar değer tipinde veri saklar.

public ActionResult Index()
        {
            HttpCookie cookie = new HttpCookie("userName","oktayaltan72"); // Cookie oluşturdum
           // cookie.Expires = DateTime.Now.AddDays(1); //1 gün sonra cookie öldürmek için
            HttpContext.Response.Cookies.Add(cookie); //Kullanıcının makinasına kaydedilmesi komutunu vermemiz gerekiyor

            return RedirectToAction("Index2");
        }
        public ActionResult Index2()
        {
            if (HttpContext.Request.Cookies["userName"] !=null)
            {
                ViewBag.userName = HttpContext.Request.Cookies["userName"].Value;
            }
            else
            {
                ViewBag.userName ="Cookie Tanımlanmamaıştır";

            }
            return View();
        }
        public ActionResult Index3()
        {
            if (HttpContext.Request.Cookies["userName"] != null)
            {
                //HttpContext.Request.Cookies.Remove("userName");
                HttpContext.Response.Cookies["userName"].Expires = DateTime.Now.AddSeconds(2);
                ViewBag.userName = "Cookie Silindi";
            }
            else
            {
                ViewBag.userName = "Cookie Bulunamadı";

            }
            return RedirectToAction("Index2");
        }












Hiç yorum yok:

Yorum Gönder