【发布时间】:2017-10-06 12:26:28
【问题描述】:
我正在尝试在 .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 请求,您也希望将用户重定向到登录页面?
-
是的,如果会话超时,用户应该被重定向到 ajax 请求中的登录页面
标签: c# ajax asp.net-core asp.net-core-mvc session-timeout