[英]Handling session timeout in mvc
我正在嘗試在.net核心應用程序中實現會話超時。 在非ajax請求/完整回發中,重定向到登錄頁面可以正常工作,但在ajax請求的情況下則無法正常工作。 登錄頁面顯示在ajax請求的布局/當前頁面內。
我編寫了一個中間件,它將首先調用控制器方法,並在其中編寫重定向登錄。以下是我的代碼。
中間件
app.Use(async (ctx, next) =>
{
if (ctx.GetTenantContext<AppTenant>() == null && !ctx.Request.Path.ToString().Contains("/Home/Redirect"))
{
string redirect = "/Home/Redirect/";
if (ctx.Request.Path.ToString().Contains("Admin"))
{
redirect = "/Home/Redirect/Admin";
}
else
{
redirect = "/Home/Redirect/Trainee";
}
ctx.Response.Redirect(redirect, true);
}
else
{
await next();
}
});
家庭控制器
[Route("/Home/Redirect/{AppType?}")]
public async Task<IActionResult> Redirect()
{
string appType = string.Empty;
string clientName = string.Empty;
if (!string.IsNullOrEmpty(Convert.ToString(RouteData.Values["AppType"])))
{
appType = Convert.ToString(RouteData.Values["AppType"]);
}
await _signInManager.SignOutAsync();
HttpContext.Session.Clear();
if (!string.IsNullOrEmpty(appType))
{
if (appType == "Admin")
{
if (HttpContext.Request.Cookies != null)
{
if (HttpContext.Request.Cookies["clientnamebe"] != null)
{
clientName = HttpContext.Request.Cookies["clientnamebe"].ToString();
}
}
return RedirectToRoute(new
{
controller = "Admin",
action = "Login",
clientname = clientName
});
}
else
{
if (HttpContext.Request.Cookies != null)
{
if (HttpContext.Request.Cookies["clientnamefe"] != null)
{
clientName = HttpContext.Request.Cookies["clientnamefe"].ToString();
}
}
return RedirectToRoute(new
{
controller = "Account",
action = "Login",
clientname = clientName
});
}
}
return View();
}
在登錄方法中,我只是返回一個視圖
[Route("Account/Login/{clientname}", Name = ApplicationType.FRONTEND)]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true, Duration = 0)]
public async Task<IActionResult> TraineeLogin(string returnUrl)
{
Return View();
}
我的ajax請求 ,盡管我只是在單擊選項卡時將相關的操作結果加載到div中。
$('#tabstrip a').click(function (e) {
e.preventDefault();
var tabID = $(this).attr("href").substr(1);
localStorage.setItem("ClientCourseTab", '#'+tabID);
$("#" + tabID).html("");
var link = '@Url.Action("-1", "Course")';
link = link.replace("-1", tabID);
$("#" + tabID).load(link); // here actual request made
var appendValue = tabID.replace('_FrontEnd', '');
var appendValue = appendValue.replace('_', '');
window.location.hash = appendValue;
$(this).tab('show');
});
任何對此的幫助表示贊賞!
在這種情況下,服務器確實會為ajax請求返回Redirect響應,但不會將用戶重定向到Login頁面。 為什么? 原因是HTTP重定向是由瀏覽器隱式處理的,實際上從來沒有到達ajax成功回調 。 瀏覽器將處理重定向,並提供包含重定向目標內容(本例中為登錄頁面)的200代碼。
這並不像聽起來那么簡單,很少有解決方法,但是所有這些都非常復雜。 這是您可以嘗試實現的一種解決方案:
另一個解決方案是在每個頁面上以特定間隔運行一些javascript代碼,以檢查會話是否已過期(通過查詢服務器,這會使事情更加復雜)。 每當此javascript代碼檢測到會話已過期時,應立即將用戶帶到登錄頁面,而不是等待ajax請求被觸發。 查詢服務器的問題是,如果服務器上的auth票證有某種滑動期限 ,則該票證可能會更新,並且會話可能永不過期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.