Thứ Ba, 2 tháng 10, 2012

Lưu giữ Session của bạn với JQuery và ASP.NET

Khi bạn làm việc với Session trong ASP.NET điều đầu tiên bạn cần quan tâm đó là làm sao để Session không bị Timeout, mặc định thời gian timeout của 1 Session được cấu hình trong file Web.Config và có thời gian là 20 phút.

Ví dụ khi khách hàng đăng nhập vào hệ thống của bạn nếu Session timeout điều đó có nghĩa với khách hàng sẽ phải đăng nhập lại, điều này thường gây khó chịu cho một số người.

Để tránh điều này chúng ta sẽ sử dụng JQuery Ajax để cách 10s chúng ta sẽ lấy lại Session cho người dùng thông qua file Generic Handler (ASHX)

Đầu tiên bạn hãy tạo 1 file Generic Handler (ASHX) có tên là KeepSessionAlive.ashx

Code như sau:

code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class KeepSessionAlive : IHttpHandler ,IRequiresSessionState
{
 
    public void ProcessRequest(HttpContext context)
    {
        //khoi tao lai Session
        context.Session["KeepSessionAlive"] = DateTime.Now;
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Using thêm

code
1
using System.Web.SessionState;

trong class này bắt buộc chúng ta phải kế thừa thêm từ Interface IRequiresSessionState bởi nếu không khi biên dịch bạn sẽ gặp lỗi ở context.Session

Tiếp theo bạn vào file Default.aspx viết Javascript như sau:

code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script language="javascript" type="text/javascript">
        $(function() {
            setInterval(KeepSessionAlive, 10000);
        });
  
        function KeepSessionAlive() {          
            $.post("/KeepSessionAlive.ashx", null, function() {
                $("#result").append("<p>Session is alive and kicking!<p/>");
            });  
        }  
    </script>
    <h2>Will my session die?</h2>  
    <div id="result"></div>

Khi trang web được load lên tôi sẽ setInterval cho hàm KeepSessionAlive() là 10s 1 lần có nghĩa cứ 10s tôi sẽ gọi lại hàm KeepSessionAlive().

Trong hàm KeepSessionAlive() tôi sẽ post lên file KeepSessionAlive.ashx để khởi tạo lại Session.

Theo DotnetCurry

Không có nhận xét nào:

Liên kết quảng cáo :