3 回答

TA貢獻(xiàn)1829條經(jīng)驗 獲得超9個贊
您可以編寫一個自定義[Authorize]屬性,該屬性將返回JSON,而不是在未經(jīng)授權(quán)訪問的情況下拋出401異常,這將允許客戶端腳本優(yōu)雅地處理場景:
[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貢獻(xiàn)2003條經(jīng)驗 獲得超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 關(guān)注
- 631 瀏覽
添加回答
舉報