Zeshan Zeshan - 3 months ago 33
ASP.NET (C#) Question

ASP.NET MVC Routing - Redirect to Route when Action Name and Url is same

I need to redirect on different action based on role. I have made following changes to RouteConfig.cs.

RouteConfig.cs

routes.MapRoute(
name: "borrower",
url: "borrower",
defaults: new { controller = "Home", action = "Borrower" });

routes.MapRoute(
name: "broker",
url: "broker",
defaults: new { controller = "Home", action = "Broker" });

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });


Here is my controller

HomeController.cs

public class HomeController : Controller
{
public ActionResult Index()
{
if (UserPrincipal.Current.Identity.IsAuthenticated)
{
if (UserPrincipal.Current.IsInRole("Broker"))
{
return RedirectToRoute("broker");
}
else if (UserPrincipal.Current.IsInRole("Borrower"))
{
return RedirectToRoute("borrower");
}
}
return View();
}

public ActionResult Broker()
{
return View();
}
public ActionResult Borrower()
{
return View();
}
}


Code flow is working properly till
return RedirectToRoute("")
but after this code flow never goes to related/appropriate action and empty view is returned.

NOTE: Both Broker and Borrower views are not empty they have static text.

In network tab you can see proper redirect is being performed and URL in browser is being set to route URL.

enter image description here

RedirectToRoute("Broker")
result in
302
response and user is redirected to
abc.com/broker
as it should but
abc.com/broker
does not hit
Broker
action method in
HomeController
and empty view is returned. According to
RouteConfig.cs
it should hit
Broker
action method.

Please point out what I'm doing wrong here.

Answer

It turned out that I had a directory named "Borker" and "Borrower" at root of the web project. Due to this MVC routing module was being ignored and requests (abc.com/broker and abc.com/borrower) was moved to these directory. So I renamed these directories and everything worked as expected :)

Comments