C# MVC4部分视图授权加载Ajax
我将尽可能地解释这一点。所以,这是我的问题 我有一个控制器,它有两个操作(我们将使用索引操作称为Controller1),一个使用HttpGet属性,另一个使用HttpPost属性,两个都使用Authorize属性来确保对某人进行身份验证 Controller1.Index视图使用局部视图,该视图调用名为_命令的视图(也在Controller1控制器上)。此部分视图在控制器中还具有与其关联的Authorize属性 如果用户未经授权,他们将被强制登录到具有与其关联的Get和Post属性(索引操作)的登录控制器(LoginController) Controller1.Index通过一个名为GetRecord的操作调用局部视图。如果记录存在,它将呈现分部(返回一个PartialView),如果不存在,它几乎只呈现一个空白DIV。这都是通过Jquery.ajax调用使用POST-ajax调用完成的 但是,问题是当用户在页面上坐了很长时间,并且他们的会话过期,并且他执行了一个jquery事件(例如,更改触发ajax调用以更新部分的下拉列表),部分将使用Login.Index视图呈现(并调用LoginController.Index GET操作),其中_命令应为partial 现在我的问题是,如何强制登录屏幕从任何部分调用中“踢出自己”,然后重新加载为首页 我试过一些不起作用的东西。例如,我在登录GET中尝试了Request.IsAjaxRequest,但没有效果。我还尝试了Ischildation,但没有效果。两者都返回了FALSEC# MVC4部分视图授权加载Ajax,c#,asp.net-mvc,asp.net-mvc-4,partial-views,C#,Asp.net Mvc,Asp.net Mvc 4,Partial Views,我将尽可能地解释这一点。所以,这是我的问题 我有一个控制器,它有两个操作(我们将使用索引操作称为Controller1),一个使用HttpGet属性,另一个使用HttpPost属性,两个都使用Authorize属性来确保对某人进行身份验证 Controller1.Index视图使用局部视图,该视图调用名为_命令的视图(也在Controller1控制器上)。此部分视图在控制器中还具有与其关联的Authorize属性 如果用户未经授权,他们将被强制登录到具有与其关联的Get和Post属性(索引操作)
其他人对我如何解决这个问题有什么想法吗?以下是我在最近的项目中所做的工作 首先,在全局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;
}
}
}
});
有一些原因(我现在想不起来了,但我很确定我是从其他地方得到信息的),你不能依赖标准的unauth状态代码,因此必须用403覆盖它。希望这有帮助 可能重复几十个SO问题,这些问题可以在谷歌上搜索为“asp.net捕获未经授权的ajax请求”。
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
}