Asp.net MVC访问框架页中嵌套的iframe页面时,如果session或cookie过期,登录验证超时怎样自动跳转到登录页 写代码前后端代码
时间: 2024-03-20 19:43:44 浏览: 14
好的,下面是前后端代码实现的思路:
后端代码:
1. 在BaseController中添加一个OnActionExecuting方法,用于判断用户是否登录,如果未登录,则跳转到登录页面。
```csharp
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContext.Session;
if (session["UserId"] == null)
{
filterContext.Result = new RedirectResult("~/Account/Login");
}
base.OnActionExecuting(filterContext);
}
}
```
2. 在需要登录验证的Controller中,继承BaseController即可。
```csharp
public class HomeController : BaseController
{
public ActionResult Index()
{
return View();
}
}
```
前端代码:
1. 在前端页面中,使用`setInterval()`函数定时向后端发送一个心跳请求,以保持会话的活跃状态。
```javascript
setInterval(function () {
$.ajax({
url: "/HeartBeat",
type: "get",
dataType: "json",
success: function (data) {
//处理返回的数据
},
error: function () {
//处理请求失败的情况
}
});
}, 300000); //5分钟发送一次请求
```
2. 在前端页面中,使用`window.addEventListener()`函数监听所有的ajax请求,如果返回的状态码为401,则跳转到登录页面。
```javascript
window.addEventListener('load', function () {
$(document).ajaxComplete(function (event, xhr, options) {
if (xhr.status == 401) {
window.location.href = '/Account/Login';
}
});
});
```
3. 在前端页面中,如果页面中嵌套了iframe,则在iframe加载完成后,判断iframe中的页面是否需要登录验证,如果需要,则向iframe中发送一个心跳请求。
```javascript
function checkIframeLogin() {
var iframe = document.getElementById('myIframe');
if (iframe) {
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
var iframeUrl = iframeDoc.location.href;
if (iframeUrl.indexOf('NeedLogin') != -1) {
setInterval(function () {
iframe.contentWindow.postMessage('HeartBeat', '*');
}, 300000); //5分钟发送一次请求
}
}
}
```
在iframe中的页面中,添加一个监听事件,如果收到了来自父页面的心跳请求,则返回一个状态码,用于前端页面中的跳转。
```javascript
window.addEventListener('message', function (event) {
if (event.data == 'HeartBeat') {
$.ajax({
url: '/HeartBeat',
type: 'get',
dataType: 'json',
success: function (data) {
//处理返回的数据
},
error: function () {
parent.window.location.href = '/Account/Login';
}
});
}
});
```
上述代码中,`parent.window.location.href = '/Account/Login';`表示在父页面中跳转到登录页面。
希望以上代码可以帮助到您,如有任何疑问,请随时提出。