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
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.