“Child actions are not allowed to perform redirect

2019-01-12 09:36发布

问题:

I have this error:

Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.

with inner exception:

Child actions are not allowed to perform redirect actions.

Any idea why this happening?

Incidentally, the error is happening on this line:

@Html.Action("Menu", "Navigation")

The Menu Action in the Navigation Controller looks like this:

public ActionResult Menu()
{
    return PartialView();
}

回答1:

This is not allowed because MVC has already started Rendering the View to the browser (client). So the MVC Frameworks blocks this, because the client already receives data (html). As long as the rendering is in progress you not able to redirect in your child view.

You can return RedirectToAction instead.



回答2:

This happened to me because I had [RequireHttps] on the Controller, and a child action was called from a different controller. The RequireHttps attribute caused the redirect



回答3:

Instead of

@Html.Action("Menu", "Navigation")

Use

@Url.Action("Menu", "Navigation")

Worked for me :)



回答4:

I had same situation like Doug described above

My solution: 1)Created custom Controller Factory. It's need for getting ControllerContext in my custom https attribute.

public class CustomControllerFactory : DefaultControllerFactory
    {
        public override IController CreateController(RequestContext requestContext, string controllerName)
        {
            var controller = base.CreateController(requestContext, controllerName);
            HttpContext.Current.Items["controllerInstance"] = controller;
            return controller;
        }
    }
}

2)In Application_Start function from Global.asax file wrote next:

ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());

3)Defined custom https attribute:

public class CustomRequireHttpsAttribute : System.Web.Mvc.RequireHttpsAttribute
    {
        public bool RequireSecure = false;

        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {

            if (RequireSecure && !((Controller)HttpContext.Current.Items["controllerInstance"]).ControllerContext.IsChildAction)
            {
                base.OnAuthorization(filterContext);
            }
        }        
    } 

4)Using new attribute for definition of account controller: [CustomRequireHttps]



回答5:

redirect like this

string returnUrl = Request.UrlReferrer.AbsoluteUri;
return Redirect(returnUrl);

instead of

return redirect("Action","Controller")


回答6:

remove the [NoDirectAccess] annotation if added in the controller.

and in controller for the partial view

return PartialView() instead of return View()