Carlos Jimenez Bermudez Carlos Jimenez Bermudez - 4 months ago 12
jQuery Question

Hide partial views from users, but make them available to AJAX

So basically I have a single page application with Angular that is working together with ASP.NET MVC. I have a controller that has only partial views and I want the user to not be able to access them.

Normally for this I would use

[ChildActionOnly]
, but I am not calling my MVC partials from the view, but from AJAX (I do this with both jQuery and angular in different parts of the app).

Is there a way to block the user from accessing my partials, yet letting ajax get them when they click links?

Thanks,

lrb lrb
Answer

Although it sounds out of the box to handle this using an AuthorizationAttribute, you conceivably do it.

public class AjaxOnlyAuthorization : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            base.OnAuthorization(filterContext);
        }
        else
        {
            //..No Go
        }
    }
}

And then....

[AjaxOnlyAuthorization]
public MyAjaxOnlyClass
{
}

It is probally more appropriate to use an ActionFilterAttribute instead because the response format has little to do with authorization.

public class AjaxOnlyFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ...    
    }
}
Comments