ASP.NET Core Interview Question #124
How do redirects work in ASP.NET Core MVC?
Routing, Controllers & Model Binding Mid-Level Intermediate
Quick Interview Answer
A redirect tells the client to make a new request to another URL. MVC provides helpers such as Redirect(), RedirectToAction(), RedirectToRoute(), and their permanent variants.
Detailed Explanation
A redirect tells the client to make a new request to another URL. MVC provides helpers such as Redirect(), RedirectToAction(), RedirectToRoute(), and their permanent variants.
After a successful POST, applications commonly use the Post/Redirect/Get pattern: process the POST, then redirect to a GET action. This avoids accidental form resubmission when the user refreshes the page.
RedirectToAction is preferable to hard-coded URLs when navigating between MVC actions because routing generates the target URL.
Code Example
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(CreateProductViewModel model)
{
if (!ModelState.IsValid)
return View(model);
_service.Create(model);
return RedirectToAction(nameof(Index));
}