【问题标题】:Redirection from MVC area redirects me to top level action?从 MVC 区域重定向将我重定向到顶级操作?
【发布时间】:2015-10-31 03:19:22
【问题描述】:

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

考场注册地图路线

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" });

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

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-areas


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我已经更新了我的问题。如果我在两个级别都有登录模块怎么办。它会将我重定向到上述模块的登录页面。
    • 它说非静态字段、方法或属性'System.Web.Mvc.ControllerContext.RouteData.get'需要对象引用
    • @TBAG 对不起,我错过了第一行的;,它应该只是RoutData,请再试一次。
    • 那不是问题。实际上 ViewContext 不是一个静态类。所以我们无法访问 RouteData
    • @TBAG 给我一分钟,我会举个例子。
    猜你喜欢
    • 2014-01-13
    • 2017-12-03
    • 2020-08-03
    • 1970-01-01
    • 2014-02-18
    • 2010-11-30
    • 2021-06-09
    • 1970-01-01
    • 2020-01-01
    相关资源
    最近更新 更多