RedirectToAction is a ControllerBase method that returns a temporary redirection to a URL generated for another action method. Routing creates the destination instead of requiring a manually written URL. section 19.5.3
Use it when an action should redirect within the controller or to another controller:
- Select the target with an action-name string or nameof, which avoids action-name typos. section 19.5.3
- Pass route values through an anonymous object, such as new { Id = 1 }. section 19.5.3
- Omit the controller name to target the current controller; use the overload accepting action and controller names for another controller. section 19.5.3
- Choose RedirectToActionPermanent when the redirect should be permanent rather than temporary. section 19.5.3
Redirect to a product action
[HttpGet("redirect")] public IActionResult Redirect() { return RedirectToAction(nameof(GetProduct), new { Id = 1 }); } Routing generates a URL for GetProduct, and the client follows the temporary redirect to the product endpoint. section 19.5.3
Listing 19.23 Redirecting in the ProductsController.cs file in the Controllers folder
...
[HttpGet("redirect")]
public IActionResult Redirect() {
return RedirectToAction(nameof(GetProduct), new { Id = 1 });
}
...
Inspect the complete controller listing showing RedirectToAction with nameof and an anonymous route-value object. section 19.5.3
