Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC - redirecting to route gives Redirect Loop

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?!

like image 446
Andrew Avatar asked Oct 26 '08 12:10

Andrew


2 Answers

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.

like image 173
Tengiz Avatar answered Sep 19 '22 16:09

Tengiz


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.

like image 36
liggett78 Avatar answered Sep 19 '22 16:09

liggett78