[英]MVC4 Partial View Ajax Load with Authorization
我将尽力对此做一个尽可能的解释。 所以,这是我的问题。
我有一个控制器,该控制器具有两个操作(我们将使用Index操作将其称为Controller1),一个使用HttpGet属性,另一个使用HttpPost属性,并且都使用Authorize属性来确保某人已通过身份验证。
Controller1.Index视图使用局部视图,该局部视图调用称为_Commands的视图(也在Controller1控制器上)。 该局部视图在控制器中还具有与其关联的Authorize属性。
如果未授权用户,则将他们强制进入具有关联的Get和Post属性(Index操作)的Login控制器(LoginController)。
Controller1.Index通过名为GetRecord的操作调用部分视图。 如果记录存在,则呈现Partial(返回PartialView),如果不存在,则仅呈现空白DIV。 所有这些都是通过使用POST ajax调用的Jquery .ajax调用完成的。
但是,问题是,当用户坐在页面上很长一段时间并且他们的会话期满,并且他执行了jquery事件(例如,更改下拉菜单以触发ajax调用来更新部分内容)时,部分内容会被呈现使用Login.Index视图(并调用LoginController.Index GET操作),应将_Command部分放置在其中。
现在我的问题是,如何强制登录屏幕“退出”任何部分调用,然后重新加载为首页?
我已经尝试了一些不起作用的方法。 例如,我在登录GET中尝试了Request.IsAjaxRequest,但没有任何效果。 我也尝试过IsChildAction,没有任何效果。 两者都返回FALSE。
其他人对如何解决此问题有任何想法吗?
这是最近的项目对我有用的。
首先,在全局js文件中,我设置了以下内容:
$.ajaxSetup({
error: function (xhr, textStatus, errorThrown) {
//make sure this isn't caused by navigating away from the page by checking the xhr readyState
if (xhr.readyState == 4) {
switch (xhr.status) {
case 401:
case 403:
// take them to the login but hang on to their current url
//calling reload does this by leveraging the rest of our framework automagically!
window.location.reload(true);
break;
default:
bootbox.alert('<div class="text-center"><h2>An error was encountered</h2><h3>Sorry, an error has occurred. The system administrators have been notified.</h3></div>');
break;
}
}
}
});
显然,重新加载整个页面已经可以引导用户重新登录,因此我只检测到403并强制重新加载页面。 那里还有一些其他的ajax错误处理,对于您所请求的不是必需的。
现在,该403不是默认的取消身份验证状态,因此,为了实现这一点,我有一个自定义的auth属性:
public class AuthorizationRequiredAttribute : AuthorizeAttribute
{
#region Overrides of AuthorizeAttribute
public override void OnAuthorization(AuthorizationContext filterContext)
{
var skipAuthorization =
filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
if (skipAuthorization) return;
base.OnAuthorization(filterContext);
//now look to see if this is an ajax request, and if so, we'll return a custom status code
if (filterContext.Result == null) return;
if (filterContext.Result.GetType() == typeof (HttpUnauthorizedResult) &&
filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new ContentResult();
filterContext.HttpContext.Response.StatusCode = 403;
}
}
#endregion
}
有一些原因(我现在不记得了,但是很确定我是从SO上的其他地方获得的信息)的原因是您不能依赖标准的unauth状态代码,因此必须用403覆盖它。希望这对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.