Reputation: 1021
I have a custom authorization header that checks to see if the current user has a certain permission before allowing the user to call the controller action.
[HasPermission(Permission.ViewPage]
public ActionResult Index()
{
return View();
}
The HasPermission
class inherits from AuthorizeAttribute
and overrides OnAuthorization
like this:
public override void OnAuthorization(AuthorizationContext context)
{
if (!Permissions.IsUserInPermission(Permission))
{
context.Result = new ViewResult{ ViewName = "Forbidden" };
}
}
This works great with just about everything, except partial views.
When I put the authorization attribute on an action that returns a partial, the Forbidden view is returned, as expected, but it has the full layout. The full layout has all of the other elements on the page like the menu, so it looks like an iframe into another version of the site.
Is there a way to return a partial view when authorization fails on a controller action that returns a partial?
Or am I just doing this the wrong way?
Upvotes: 1
Views: 1191
Reputation: 6520
Mark the action that is returning a PartialViewResult as [ChildActionOnly] then you can check for the context.Controller.ControllerContext.IsChildAction property in your filter OnAuthorization method
if (context.Controller.ControllerContext.IsChildAction)
{
context.Result = new PartialViewResult();
}
else
{
context.Result = new ViewResult();
}
Upvotes: 1