14 Haziran 2013 Cuma

Javascript ile session kullanımı

ASP.NET uygulamalarında javascript ile session bilgilerine erişim (okuma yada yazma) Generic Handler (.ashx) kullanılabilir. Burada önemli olan IRequiresSessionState arayüzünün handler'a uygulanmasıdır. Örnekde kullanılacak handler aşağıdaki gibidir:

public class SessionHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
           
            string key = context.Request.QueryString["key"];
            string method = context.Request.QueryString["method"];
            string value = context.Request.QueryString["value"];

            if (method.ToLower() == "post")
            {
                context.Session[key] = value;
                context.Response.Write("ok");
            }

            if (method.ToLower() == "get")
            {
                context.Response.Write(context.Session[key]);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

Handler oluşturulduktan sonra artık herhangi bir sayfadan aşağıdaki şekilde bu handler çağrılabilir.
<script src="Scripts/jquery-1.8.2.min.js"></script>
<input type="button" value="Set Session" onclick="fnSetSession()" />

    <input type="button" value="Get Session" onclick="fnGetSession()" />

    <script type="text/javascript">

        function fnGetSession() {
            $.ajax({
                url: "/SessionHandler.ashx?method=get&key=kullanici",
                contentType: "text/plain; charset=utf-8",
                success: function (data) {
                    alert(data);
                },
                error: function (msg) {
                    alert(msg);
                }
            });
        }

        function fnSetSession() {
            $.ajax({
                url: "/SessionHandler.ashx?method=post&key=kullanici&value=erdem_bener",
                contentType: "text/plain; charset=utf-8",
                success: function (data) {
                    alert(data);
                },
                error: function (msg) {
                    alert(msg);
                }
            });
        }
</script>


Hiç yorum yok:

Yorum Gönder