Problem
I have created a view that posts to an action via Ajax with the expectation that the action will return the requested data or an empty string. Even better, I would like it to be configurable to return whatever value I see fit.
The problem arises when I decorate the called action with the [Authorize] attribute. If the request is not authorized and I have a loginUrl configured in my web.config, my ajax request will return the html output of my loginUrl view. That is undesirable.
Solution
I can extend the existing Authorize attribute by inheriting from the AuthorizeAttribute class. Here is the code that extends the Authorize attribute:
public class AjaxAuthorizeOverrideAttribute : AuthorizeAttribute
{
public string View { get; set; }
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
base.HandleUnauthorizedRequest(filterContext);
return;
}
filterContext.Result = new ViewResult { ViewName = View };
filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
}
}
Here is the decorator for the ajax action in the controller class:
[AjaxAuthorizeOverride(View="AjaxAuthorizeError")]
public ActionResult AjaxRequest()
{
return View();
}
Note: there is no default view page being rendered.
Original article can be found here