ASP.Net MVC - redirecting to route gives Redirect Loop
-
04-07-2019 - |
Question
This is probably one of those easy questions.. I'm trying to redirect the user after they've successfully authenticated, or return them back to the login page. But the Success page is on a different route and I can't get the redirection to work..
Here are my routes in Globals.asax:
routes.MapRoute( _
"Default", _
"{controller}/{action}/{id}", _
New With {.controller = "Login", .action = "Index", .id = ""} _
)
routes.MapRoute( _
"Stuff", _
"{controller}/{action}/{id}", _
New With {.controller = "Stuff", .action = "Index", .id = ""} _
)
I've got 2 Controllers: LoginController.vb
and StuffController.vb
. The Views/Login/Index.aspx
file contains a simple form with the code:
<form method="post" action="/Login/Authenticate">
The LoginController
contains the following code:
Function Authenticate() As RedirectToRouteResult
' authentication code commented out ;o)
Return RedirectToRoute("Stuff")
End Function
And the StuffController contains the following:
Function Index()
' show stuff..
Return View() ' return /Views/Stuff/Index.aspx
End Function
Here's what I've tried so far:
- Function Authenticate()
- Function Authenticate() As ActionResult()
- Function Authenticate() As RedirectToRouteResult()
all of which cause a Redirect Loop timeout in the browser. What am I missing?!
Solution
Could it be that your Stuff route has exactly the same form as the default one, so when you call
Return RedirectToRoute("Stuff");
the resulting url has the form: {controller}/{action}/{id}, e.g. Login/Authenticate again, since you are inside Login-controller's Authenticate action.
Try to
RedirectToAction("Index", "Stuff");
Hope that helps.
OTHER TIPS
Correct answer is good, but:
- what if you ever want to change the controller/action name from Staff/Index to something else?
-then you will need to change the values not only in global.asax, but also in all the places where you used the technique.
My suggestion:
return RedirectToRoute("Stuff", (RouteTable.Routes["Stuff"] as Route).Defaults);
Now, in this case, you don't pass the names of controller/action which is Stuff/Index accordingly. This will let you manage changes easily.
I fail to see where you are setting the authentication cookie or marking the user as having been authenticated in any way. Is that in the code that you have omitted?
try
routes.MapRoute( _
"Stuff", _
"",_
New With {.controller = "Stuff", .action = "Index", .id = ""} _
)