Reputation: 2245
I have following project structure. Where I have two Home and Account controller one inside Test Area and one at route level project. Now after login from area I want to redirect area's Home Index But it redirects me to route level Home Index.
Test Area Registration 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" }
);
}
Base level maproute
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional },
namespaces: new[] { "MVCAreaSample.Controllers" }
);
Area Redirection action method
[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");
}
I tried giving area name in route. It works in this case. But suppose I have proper authenication logic in both level than incase of
RedirectToAction("Index", "Home", new { area = "Test" });
It will give me login page of base level.
Upvotes: 4
Views: 2370
Reputation: 33305
You simply need to determine the existing area route and pass it across as a parameter in your redirect as follows:
var currentArea = RouteData.DataTokens["area"];
return RedirectToAction("Index", "Home", new { area = currentArea });
In order to go back up a level you simply specify a blank string for the area:
return RedirectToAction("Index", "Home", new { area = "" });
Upvotes: 4