Fix “Child Actions Are Not Allowed to Perform Redirect Actions” in ASP.NET MVC 5
Quick fix. A child action called with Html.Action or Html.RenderAction renders part of the parent page. Its successful result should be a partial, empty content, or another fragment. Put any full-page redirect in the top-level action.
This guide applies to ASP.NET MVC 5 on .NET Framework (System.Web.Mvc).
Locate the fragment that wanted to redirect
Check the stack trace for RedirectResult.ExecuteResult or RedirectToRouteResult.ExecuteResult. Then find the Html.Action or Html.RenderAction call in the enclosing layout, view, or partial. If the page only breaks for signed-out visitors, compare the child action’s anonymous and authenticated branches. A direct request to the same route may behave differently because it is no longer a child action.
Return a partial for each fragment state
Here an account menu has two legitimate representations. The guest partial contains an ordinary sign-in link. The full account action still uses [Authorize], so hiding or changing menu HTML does not affect access control. Put the partials in Views/Shared or in the navigation controller’s views folder.
// NavigationController.cs
[ChildActionOnly]
public ActionResult AccountMenu()
{
return PartialView(Request.IsAuthenticated
? "_SignedInMenu"
: "_GuestMenu");
}
// _Layout.cshtml
@Html.Action("AccountMenu", "Navigation")
// _GuestMenu.cshtml
@Html.ActionLink("Sign in", "Login", "Account")
Keep page-wide decisions in the outer request
If a whole page requires authentication, put [Authorize] on its top-level controller or action and use the application’s configured sign-in flow. If a valid POST needs a redirect, return it from that POST action before rendering any view. Replacing RedirectToAction with a different redirect helper in the child action does not solve the underlying request ownership problem.
Verify both paths
Open the page signed out, sign in, and return to the same page. The outer page should render in both legitimate states and show the appropriate partial. Request a protected top-level page while signed out and verify its configured authorization behavior separately.
Comments
Post a Comment