asp.net mvc [handleerror] [authorize] with JsonResult?

前端 未结 1 1747
耶瑟儿~
耶瑟儿~ 2020-12-30 02:05

What is an elegant way to leverage the existing [HandleError] and [Authorize] attributes when dealing with XHR calls from javascript?

So, say for example a method Ge

相关标签:
1条回答
  • 2020-12-30 02:14

    You don't. Right now, they don't help with JSON. However:

    I realize I can create my own [HandleJsonError] and [AuthorizeJson] attributes which return JsonResults instead of ViewResults, but then I'd have to go around and place these on any method that returns Json, and worry about Filter order etc.

    What we did is to subtype the existing attributes, and make them work conditionally:

    public sealed class AjaxAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (filterContext.Result == null)
            {
                return;
            }
            else if (filterContext.Result.GetType() == typeof(HttpUnauthorizedResult) 
                && filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new ContentResult();
                filterContext.HttpContext.Response.StatusCode = 403;
            }
        }
    }
    

    Now the JS code can look for 403 (because ASP.NET eats 401 and returns the error page) and the same attribute works for Ajax and non-Ajax. So no filter order issues.

    0 讨论(0)
提交回复
热议问题