会议是否可用

时间:2014-02-17 05:05:41

标签: c# jquery asp.net-mvc-3

我在mvc3中使用jquery ajax调用void函数。在Session出局的那个函数中,它也将成为ajax的成功函数。在发送请求之前或在ajax的成功函数内部,我需要知道会话是否可用。

控制器动作:

 protected override void Save(Query query, string queryTitle)
 {
 }

4 个答案:

答案 0 :(得分:2)

为什么不在服务器上捕获会话到期,返回HTTP 401 Unauthorized,然后在jquery中检查此响应并弹出“您的会话已过期,请再次登录”页面?

初始服务器调用所需的代码是:

protected void Save(Query query, string queryTitle)
{
    // would probably be better to refactor this bit out into its own method
    string sCookieHeader = Request.Headers["Cookie"];
    if (Context.Session != null 
        && Context.Session.IsNewSession
        && sCookieHeader != null
        && sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)
    {
        // session has expired
        if (Request.IsAuthenticated)
        {
            FormsAuthentication.SignOut();
        }
        Response.StatusCode = 401
    }
    else
    {
        // we're authenticated, so do the save
    }
}

并在客户端:

$.ajax(serverUrl, {
   data: dataToSave,
   statusCode: {
      200: function(response) {
        // all good, continue
      401: function (response) {
         // session expired!
         // show login box
         // make ajax call to reauthenticate
         // call save method again
      },
});

您的重新认证通话看起来像这样:

public ActionResult Reauthenticate(username, password) 
{
    if (IsValidUser(username, password))
    {  
      // sometimes used to persist user roles
      string userData = string.Join("|",GetCustomUserRoles());

      FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        1,                                     // ticket version
        username,                              // authenticated username
        DateTime.Now,                          // issueDate
        DateTime.Now.AddMinutes(30),           // expiryDate
        isPersistent,                          // true to persist across browser sessions
        userData,                              // can be used to store additional user data
        FormsAuthentication.FormsCookiePath);  // the path for the cookie

      // Encrypt the ticket using the machine key
      string encryptedTicket = FormsAuthentication.Encrypt(ticket);

      // Add the cookie to the request to save it
      HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
      cookie.HttpOnly = true; 
      Response.Cookies.Add(cookie);
    }
}

(改编自How to set HTTP status code from ASP.NET MVC 3?

答案 1 :(得分:0)

为什么不尝试这个?

public void Save()
{
    if (Session.IsNewSession)
    {
        throw new Exception("This session was just created.");
    }

    //Go on with save matter...
}

这应该在您的AJAX函数上返回状态500,并且应该使响应落入您定义的失败方法中。

答案 2 :(得分:0)

另一种方法是在客户端上设置setInterval(),它不断向服务器发送虚拟请求,以保持会话处于活动状态,至少在用户编辑时是这样。这可能是防止用户丢失工作的最佳方法。您也可以使用它来检测丢失连接。

答案 3 :(得分:0)

第一次加载页面时,将当前的SessionId传递给客户端并分配给本地javascript变量。接下来有一个方法在从AJAX调用Save方法之前返回当前的SessionId,比较本地根据您收到的会话ID变量。

       public string GetCurrentSessionId(){
            return HttpContext.Current.Session.SessionId;
         }

Javascript功能

      $.ajax({
          Url : 'GetCurrentSessionId',
          success : function(result){
               if(result === "LOCALSESSIONID")
                      CALL THE SAVE METHOD
               else
                  alert('Session is expired');
           }

      });
相关问题