Redirect results are action results in ASP.NET Core MVC that instruct the client’s browser to navigate to a new URL. This is commonly used after actions like form submissions, logins, or other operations where you want to transition the user to a different page. Types of Redirect Results RedirectResult: Purpose: Redirects to a specified URL (either absolute or relative). Parameters: url: The URL to redirect to. permanent: A boolean indicating whether the redirect is permanent (301 Moved Permanently) or temporary (302 Found). Defaults to false (temporary). Usage: return Redirect(“/home”); (Temporary) return RedirectPermanent(“/home”); (Permanent)
RedirectToActionResult: Purpose: Redirects to a specific action method within a controller. Parameters: actionName: The name of the action method. controllerName: The name of the controller (optional, defaults to the current controller). routeValues: An object containing route values to pass to the action (optional). permanent: A boolean indicating whether the redirect is permanent (301) or temporary (302). Usage: return RedirectToAction(“Index”); (Temporary, same controller) return RedirectToAction(“Details”, “Products”, new { id = 123 }); (Temporary, with route values) return RedirectToActionPermanent(“About”); (Permanent)
LocalRedirectResult: Purpose: Redirects to a local URL within the same application. Parameters: localUrl: The local URL to redirect to. permanent: A boolean indicating whether the redirect is permanent (301) or temporary (302). Usage: return LocalRedirect(“/products/details/456”); (Temporary) return LocalRedirectPermanent(“/about”); (Permanent)
Code // HomeController.cs [Route(“bookstore”)] public IActionResult Index() { // … validation logic (same as previous example) …
// Conditional Redirects if (someConditionIsTrue) { return RedirectToAction(“Books”, “Store”, new { id = bookId }); // Temporary, to a different action } else { return LocalRedirectPermanent($”store/books/{bookId}”); // Permanent, local redirect }
// … other redirect examples … }
Choosing the Right Redirect External vs. Internal: Use RedirectResult for external URLs and LocalRedirectResult for internal URLs. Temporary vs. Permanent: Use 301 for permanent moves, 302 for temporary ones (e.g., after form submission). Action-Specific: Use RedirectToActionResult when you want to redirect to a specific action within your application. Safety: Prefer LocalRedirectResult over RedirectResult for internal redirects to protect against open redirect attacks.