2

I have the following route set up

[HttpGet("bar")]
public IActionResult Foo()

When I access the website with "/bar", I am directed to Foo, as expected.

However, if I try to redirect to "bar", I get an error:

public async Task<IActionResult> Index()
{
    return RedirectToRoute("bar");
}

No route matches the supplied values RedirectToRoute

Why is RedirectToRoute not working?

Dan Friedman
  • 4,941
  • 2
  • 41
  • 65

1 Answers1

1

The issue is that "bar" is the route template, not the route name. In order to redirect to a specific route, that route must be named. In this case, you can do

 [HttpGet("bar", Name = "bar")]

This applies to creating routes, as well, such as Url.RouteUrl, new CreatedAtRouteResult or CreatedAtRoute, etc. The route name must exist in all cases.

The upside to having to specify the route name explicitly is that you can now change the template without breaking named routes.

 [HttpGet("bar?{data?}", Name = "bar")]
Dan Friedman
  • 4,941
  • 2
  • 41
  • 65