我有一个基于ajax的Web应用程序。我只有一个2视图,即登录和主视图本身,其余的是将使用ajax请求调用的PartialView。
如果我将会话检查器放在partialviews(通过ActionFilters)中,它将返回登录视图,它将在我的ajax成功后显示,这不是我想要的结果,因为我希望主页本身是重定向回登录屏幕。
我想到的一个解决方案是使用javascript超时,它将检查会话/身份验证是否仍然存在给定一组间隔,但我不知道这种做法是否良好。
有人可以建议我做什么吗?
我有2个视图,login
和mainframe
,然后大约30 PartialViews
。
答案 0 :(得分:1)
我过去曾使用Javascript计时器轮询服务器以测试会话是否仍处于活动状态。如果我收到403然后重定向到登录页面。
var AutoLogout = {};
AutoLogout.pollInterval = 60000; // Default is 1 minute.
// Force auto logout when session expires
AutoLogout.start = function (heartBeatUrl, sessionExpiredUrl, interval) {
if (interval) AutoLogout.pollInterval = interval;
var timer = $.timer(function() {
checkSession(heartBeatUrl, sessionExpiredUrl, timer);
});
timer.set({ time: AutoLogout.pollInterval, autostart: true });
};
// Check the session serverside to see if we need to auto-logout
// if the clientActivity flag is set then the session will be extended before checking.
// if the session is still alive then set the next timer interval to be the time returned from the server.
function checkSession(sessionUrl, sessionExpiredUrl, timer) {
$.ajax(sessionUrl,
{ type: "post",
contentType: "application/json",
success: function (result)
{
// update the timer poll interval based on return value.
try {
var r = ko.toJS(result);
timer.set({
time: r.TimeoutMilliseconds ? r.TimeoutMilliseconds : AutoLogout.pollInterval, autostart: true
});
}
catch(e) { }
},
error: function(e)
{
// do nothing
},
statusCode:
{
403: function ()
{
window.location.href = sessionExpiredUrl;
},
401: function ()
{
window.location.href = sessionExpiredUrl;
}
}
});
}
然后当您加载页面时,请为您的应用程序调用带有必要URL的AutoLogout.start。
注意:我在此示例中使用了Knockout JS来解析从服务器请求返回的数据,但这取决于您。
答案 1 :(得分:0)
我会尽力解决你的问题
我建议将你的逻辑放入动作过滤器
public class AuthorizeActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(FilterExecutingContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContext.Session;
Controller controller = filterContext.Controller as Controller;
if (controller != null)
{
if (session != null && session ["authstatus"] == null)
{
filterContext.Result =
new RedirectToRouteResult(
new RouteValueDictionary{{ "controller", "Login" },
{ "action", "Index" }
});
}
}
base.OnActionExecuting(filterContext);
}
}