2012-05-14 6 views
7

Ho una chiamata ajax a MVC che restituisce una vista parziale. Tutto ciò va bene fino alla fine della sessione o alla scadenza del cookie. Quando faccio la chiamata ajax mostra il contenuto all'interno di un div che doveva essere per la partialview. Come posso rilevare che la mia sessione è scaduta durante la chiamata Ajax e reindirizzare correttamente a schermo intero/paginaMVC 3/Jquery AJAX/sessione scade/C# - Gestione sessione timeout durng chiamata ajax

+0

sto affrontando lo stesso problema, hai trovato una soluzione per questo? – oqx

risposta

4

È possibile creare un timer sul client con javascript che mostrerà una finestra di dialogo all'utente quando la sessione è scaduta . Dovresti semplicemente impostare il valore del timer su qualsiasi intervallo di tempo della tua sessione. Quindi, su richiesta Ajax, ripristinerà anche il conto alla rovescia.

var g_sessionTimer = null; 
function uiSessionInit() { 
    id = "uiTimeout"; 
    timeout = 3600000 * 24; // 1 day timeout 
    uiSessionSchedulePrompt(id, timeout); 
    $('body').ajaxStart(function() { 
     // reset timer on ajax request 
     uiSessionSchedulePrompt(id, timeout); 
    }); 
} 
function uiSessionSchedulePrompt(id, timeout) { 
    if (g_sessionTimer) 
     clearTimeout(g_sessionTimer); 
    g_sessionTimer = setTimeout(function() { uiSessionExpiring(id); }, timeout); 
} 
function uiSessionExpiring(id) { 
    // create a dialog div and use this to show to the user 
    var dialog = $('<div id="uiTimeout"></div>').text("Your session with has timed out. Please login again."); 
    $('body').append(dialog); 
    $('#uiTimeout').dialog({ 
      autoOpen: true, 
      modal: true, 
      title: 'Expired Session', 
      buttons: { 
       "OK": function(){ 
        $(this).dialog('close'); 
       } 
      }, 
      close: uiSessionDialogClose 
    }); 
} 

function uiSessionDialogClose(){ 
    // take user to sign in location 
    location = 'http://www.mypage.com'; 
} 
5

Suggerirei incapsulare tutte le vostre richieste in un elemento di involucro:

public class JsonResponse<T> 
{ 
    public JsonResponse() 
    { 
    } 

    public JsonResponse(T Data) 
    { 
     this.Data = Data; 
    } 

    public T Data { get; set; } 
    public bool IsValid { get; set; } 
    public string RedirectTo { get; set; } 
} 

Quale modello che si desidera inviare al vostro cliente è nei dati.

Per ottenere il RedirectTo popolato, utilizzo un attributo GlobalAuthorize in Global.Asax e aggiunto handle for HandleUnauthorizedRequests.

public sealed class GlobalAuthorize : AuthorizeAttribute 
{ 
    protected override void HandleUnauthorizedRequest 
     (AuthorizationContext filterContext) 
    { 
     if (filterContext.HttpContext.Request.IsAjaxRequest()) 
     { 
      filterContext.Result = new JsonResult 
      { 
       Data = new JsonResponse<bool> 
         { 
          IsValid = false, 
          //RedirectTo = FormsAuthentication.LoginUrl 
          RedirectTo = "/" 
         }, 
       JsonRequestBehavior = JsonRequestBehavior.AllowGet 
      }; 
     } 
     else 
     { 
      base.HandleUnauthorizedRequest(filterContext); 
     } 
    } 

Inoltre, ho incapsulato tutti mie richieste Ajax in una singola funzione che controlla per il RedirectTo.

function global_getJsonResult(Controller, View, data, successCallback, completeCallback, methodType) 
{ 
    if (IsString(Controller) 
     && IsString(View) 
     && !IsUndefinedOrNull(data)) 
    { 
     var ajaxData; 
     var ajaxType; 

     if (typeof (data) == "string") 
     { 
      ajaxData = data; 
      ajaxType = "application/x-www-form-urlencoded" 
     } 
     else 
     { 
      ajaxData = JSON.stringify(data); 
      ajaxType = "application/json; charset=utf-8"; 
     } 
     var method = 'POST'; 

     if (!IsUndefinedOrNull(methodType)) 
     { 
      method = methodType; 
     } 

     var jqXHR = $.ajax({ 
      url: '/' + Controller + '/' + View, 
      data: ajaxData, 
      type: method, 
      contentType: ajaxType, 
      success: function(jsonResult) 
      { 
       if (!IsUndefinedOrNull(jsonResult) 
        && jsonResult.hasOwnProperty("RedirectTo") 
        && !IsUndefinedOrNull(jsonResult.RedirectTo) 
        && jsonResult.RedirectTo.length > 0) 
       { 
        $.fn.notify('error', 'Login Expired', 'You have been inactive for a prolonged period of time, and have been logged out of the system.'); 
        window.setTimeout(function() { window.location = jsonResult.RedirectTo }, 5000); 
       } 
       else if (IsFunction(successCallback)) 
       { 
        successCallback(jsonResult, Controller + '/' + View); 
       } 
      }, 
      error: function(jqXHR, textStatus, errorThrown) 
      { 
       if (errorThrown != 'abort') 
       { 
        $.fn.notify('error', 'AJAX Connection Error', textStatus + ': ' + errorThrown); 
       } 

      }, 
      complete: function(jqXHR, textStatus) 
      { 
       if (IsFunction(completeCallback)) 
       { 
        completeCallback(jqXHR, textStatus, Controller + '/' + View); 
       } 
      } 
     }); 

     return jqXHR; 
    } 
} 
+0

Ho provato a usare la tua strada, il mio HandleUnauthorizedRequest funziona perfettamente, ma non viene mai in un metodo global_getJsonResult(), puoi darmi un esempio di come hai incapsulato il tuo metodo jquery? – Bharat

+0

Non sai cosa intendi. L'esempio precedente ha un metodo che incapsula richieste Ajax e tutte le richieste usano quel metodo nel mio codice JS. –