不允许子操作执行重定向操作 - MVC

Mr.*_*Ken 1 asp.net-mvc custom-action-filter action-filter asp.net-mvc-3 asp.net-mvc-4

我有一个_layout加载菜单:

...
@Html.Action("MenuRole","Menu")
...
Run Code Online (Sandbox Code Playgroud)

在Action MenuRole我检查与Action Filter的会话:

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

并在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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

当会话超时时,_layout在@ Html.Action("MenuRole","Menu")中显示错误:不允许子操作执行重定向操作

Moh*_*rag 7

我有同样的例外,我通过检查解决了它IsChildAction:

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

这解决了我的问题