从 MVC 区域重定向将我重定向到顶级操作?

Redirection from MVC area redirects me to top level action?

我有以下项目结构。我有两个家庭和帐户控制器,一个在测试区域内,一个在路线级项目中。现在从区域登录后,我想重定向区域的主页索引,但它会将我重定向到路由级别的主页索引。

测试区注册MapRoute

public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Test_default",
                "Test/{controller}/{action}/{id}",
                new { controller = "Account", action = "Login", id = UrlParameter.Optional },
                namespaces: new[] { "MVCAreaSample.Areas.Test.Controllers" }
            );
        }

基础地图路线

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional },
                namespaces: new[] { "MVCAreaSample.Controllers" }
            );

区域重定向操作方法

[HttpPost]
        public ActionResult Login(TestModel test)
        {
            var candidateContext = "LoginContext";


            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(2, candidateContext, DateTime.Now, DateTime.Now.AddMinutes(60), true, "Manjay");
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

            //Check required for code contracts.
            if (System.Web.HttpContext.Current != null)
            {
                System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);

                if (System.Web.HttpContext.Current.Session != null)
                    System.Web.HttpContext.Current.Session["LoginContext"] = candidateContext;
            }


            return RedirectToAction("Index", "Home");
        }

我试过在路线中给出区域名称。它适用于这种情况。但是假设我在两个级别都有适当的认证逻辑而不是

RedirectToAction("Index", "Home", new { area = "Test" });

它将给我基本级别的登录页面。

您只需确定现有的区域路由并将其作为参数传递到您的重定向中,如下所示:

var currentArea = RouteData.DataTokens["area"];
return RedirectToAction("Index", "Home", new { area = currentArea });

为了返回上一级,您只需为该区域指定一个空白字符串:

return RedirectToAction("Index", "Home", new { area = "" });