在 MVC 5 中,我重写 HandleUnauthorizedRequest()
并检查请求是否来自 AJAX。
我还注册了一个全局ajaxComplete
,用于处理401 AJAX请求,但是进入HandleUnauthorizedRequest()
后状态码仍然是200。
问题:我是否必须在函数 HandleUnauthorizedRequest()
中手动更改 filterContext
中的状态代码?
检测到未经授权的 AJAX 请求
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
// <-- in here
filterContext.Result = new JsonResult
{
Data = new
{
returnUrl = "foo"
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
全局ajax完成注册
$(document).ajaxComplete(function (e, xhr, settings) {
console.log('xhr.status: "' + xhr.status +'"'); // 200 - i want 401
if(xhr.status === 401) {
window.location.replace(urlHelper.getUrlNotAuthorized());
}
});
“在我找到 ajaxComplete 的解决方案之前,该解决方案可以工作,但已被破解。
它检查用户请求是否获得授权。缺点是每次发出请求时我都必须检查 isAuthorized() 。这就是为什么我想使用全局 ajaxComplete,这样我就不会错过任何一个。”:
检查用户 AJAX 请求是否已授权
isAuthorized = function (result) {
try {
var obj = JSON && JSON.parse(result) || $.parseJSON(result);
// Here, obj can still be a parsed JsonResult, from when getting GetDatatableRows(), so we also need to check on returnUrl which is distinct
// obj will only contain returnUrl if the JSON was returned from Shield validation
if (obj && obj.returnUrl) {
window.location.replace(urlHelper.getUrlNotAuthorized() + '?returnUrl=' + encodeURIComponent(obj.returnUrl));
return false;
}
} catch (e) {
}
return true;
};
AJAX 请求,结果是部分 View 或 JSON
partialViewService.changePartialViewService(url, data)
.done(function (result) {
if (isAuthorized(result)) {
// use result
}
});
最佳答案
是的 - 我还没有检查过这一点,但尝试添加指示的行。指定代码 401 不会过滤到您想要的结果。 (我怀疑这是由于身份拦截代码 401 造成的):
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
// Add this (code 401 does not work)
filterContext.HttpContext.Response.StatusCode = 412;
// <-- in here
filterContext.Result = new JsonResult
{
Data = new
{
returnUrl = "foo"
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
关于javascript - 未经授权的 AJAX 请求返回状态代码 200 而不是 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35863217/