Ammar Mehmood
Ammar Mehmood

Reputation: 27

ASP.NET MVC redirect to action Redirect Loops

I am learning asp.net MVC and I was trying Redirect to action and I tried the following code and I keep getting Redirect Loop Error. This is the Controller class in which I am getting an error

  public class CuisineController : Controller
{
    // GET: Cuisine
    public ActionResult Search(string name)
    {


        return RedirectToAction("About","Cuisine");

    }
    public ActionResult Index()
    {
        return Content("This is Index");
    }
    public ActionResult About()
    {
        return Content("this is About");
    }
}

I have also created a route of my own other than the Default route

 routes.MapRoute(name: "Cuisine",
            url: "cuisine/{name}",
            defaults: new { controller = "Cuisine", action = "Search", name = UrlParameter.Optional });

When I try to access the Cuisine controller it gives me a redirect loop error. Thank you

Upvotes: 1

Views: 2389

Answers (4)

patrikulus
patrikulus

Reputation: 1

You need to restore controller action pattern. Just change url: "cuisine/{name}" to url: "cuisine/{action}/{name}"

Upvotes: 0

Nikolay
Nikolay

Reputation: 12245

It looks like you want to make {name} part of URL. You can use attribute routing instead of changing default routing, it does not have such global "destructive" effects (explained in other answers) at least, and looks it's what you are actually after :)

[Route("Search/{name}")]
public ActionResult Search(string name)
{
    return RedirectToAction("About", "Home");
}

See more about attribute routing here (for this to work, don't forget to add routes.MapMvcAttributeRoutes() if it is not there yet).

Upvotes: 0

Shyju
Shyju

Reputation: 218762

In your routeConfig, you have a route defined for "cuisine/{name}" and it will be sent to the Search action method.

In your Search action method, You are redirecting to the About, Which is cuisine/About. This is matching with the route you defined cuisine/{name} so it will send the request to Search action again. The same process will keep running. That is why you are getting the redirect loop

You should either delete this specific route you defined or rename the url pattern for cusine search to prevent the redirect loop.

 routes.MapRoute(name: "Cuisine",
            url: "searchcuisine/{name}",
            defaults: new { controller = "Cuisine", action = "Search", 
                                                          name = UrlParameter.Optional });

Upvotes: 2

Erik Philips
Erik Philips

Reputation: 54638

This should be pretty obvious:

routes.MapRoute(name: "Cuisine",
url: "cuisine/{name}",
defaults: new { controller = "Cuisine", action = "Search", name = UrlParameter.Optional })

Says all urls that start with cuisine/ use the Search method on the CuisineController.

/Cuisine/About starts with that url, so it willl always use the Search method.

Upvotes: 2

Related Questions