3 回答
TA贡献1829条经验 获得超9个赞
您可以编写一个自定义[Authorize]属性,该属性将返回JSON,而不是在未经授权访问的情况下抛出401异常,这将允许客户端脚本优雅地处理场景:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new JsonResult
{
Data = new
{
// put whatever data you want which will be sent
// to the client
message = "sorry, but you were logged out"
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
然后用它以及在客户端上装饰您的控制器/动作:
$.get('@Url.Action("SomeAction")', function (result) {
if (result.message) {
alert(result.message);
} else {
// do whatever you were doing before with the results
}
});
TA贡献2003条经验 获得超2个赞
我不会将JsonRequestBehavior更改为AllowGet。相反,我建议:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class MyAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
OnAuthorizationHelp(filterContext);
}
internal void OnAuthorizationHelp(AuthorizationContext filterContext)
{
if (filterContext.Result is HttpUnauthorizedResult)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.HttpContext.Response.End();
}
}
}
}
并添加全局js ajax错误处理程序:
$(document).ajaxError(function (xhr, props) {
if (props.status === 401) {
location.reload();
}
}
- 3 回答
- 0 关注
- 599 浏览
添加回答
举报