3

I have a _layout load menu as :

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

in Action MenuRole i check session with Action Filter :

[CheckSession]
[ChildActionOnly]
public ActionResult MenuRole()
{
    ....
    return PartialView("_LoadMenu",menuModel);
//_LoadMenu is partial view to show menurole
}

And in Action Filter :

public class CheckSession : ActionFilterAttribute, IActionFilter
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var ctx = filterContext.HttpContext;

            //if Session == null => Login page
            if (ctx.Session["Username"] == null)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Login" }));

            }

            base.OnActionExecuting(filterContext);
        }
    }

When session timeout, _layout show error in @Html.Action("MenuRole","Menu") : Child actions are not allowed to perform redirect actions

Mr.Ken
  • 87
  • 2
  • 11
  • 3
    The message is self explanatory - you cannot use `RedirectToRouteResult()` in a method marked `ChildActionOnly` (which you are doing if `Session["Username"]` is `null`) –  Jul 26 '16 at 09:31
  • I know it. Would you have it any other way ? – Mr.Ken Jul 26 '16 at 09:34
  • 1
    Your problem comes from here: `new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Login" }));` executed after view already rendered. Probably using `@Url.Action` instead of `@Html.Action` may solve this issue. – Tetsuya Yamamoto Jul 26 '16 at 09:37
  • If you want the `RedirectToRouteResult` code, then remove the `ChildActionOnly` attribute. The behavior is expained in [this answer](http://stackoverflow.com/questions/25015833/child-actions-are-not-allowed-to-perform-redirect-actions-after-setting-the-sit) –  Jul 26 '16 at 09:39
  • @TetsuyaYamamoto : Thanks for reply. But it's not show my menurole . Stephen Muecke : I removed it, but it's not working ! – Mr.Ken Jul 26 '16 at 09:58
  • 1
    Sorry, I meant the `[CheckSession]` attribute. `@Html.Action()` means your calling a child action and you cannot redirect within it as explained in the link above. –  Jul 26 '16 at 10:01
  • I got it. i must find anther way. Thanks for help ! – Mr.Ken Jul 27 '16 at 00:33

1 Answers1

9

I had the same exception and I solved it by checking IsChildAction like :

        //if Session == null => Login page
        if (ctx.Session["Username"] == null && !filterContext.IsChildAction)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Login" }));
        }

that solved me the problem

Mohamed Farrag
  • 1,682
  • 2
  • 19
  • 41
  • This problem is : **my check session attribute can not be used on child actions**. Thanks for reply ! – Mr.Ken Jul 27 '16 at 00:31