An HTTP redirect sends a client to another URL instead of completing the interaction at the URL it first requested. In ASP.NET Core, redirects appear in controller action results, form handling, and production error handling. The client must follow the redirect to receive the destination response. section 19.5.3 section 27.2
Choose the redirect to match the destination:
- Use Redirect("/api/products/1") in a controller action for a temporary redirect to a URL. RedirectPermanent is the permanent alternative. section 19.5.3
- Use RedirectToAction(nameof(GetProduct), new { Id = 1 }) to target an action, or RedirectToRoute with route values to target a route. Permanent action-redirect methods are also available. section 19.5.3
- Use LocalRedirect or LocalRedirectPermanent when the destination comes from user input and must remain local. These methods throw an exception for a nonlocal URL, helping prevent open redirects to untrusted sites. section 19.5.3
Redirect after a form POST
A browser requests a form with GET, submits its data with POST, then follows a redirect to a results page. This Post/Redirect/Get sequence lets the user reload the results without submitting the POST again. In a Razor Pages implementation, the POST handler stores form data in TempData and redirects to a page that displays it. section 27.2 section 27.2.2
A redirect can also replace a bare production error response with a friendlier page: configure UseExceptionHandler("/error.html") and UseStaticFiles(), then provide wwwroot/error.html. Keep the error page simple; an exception while handling the original exception can make the result more confusing. section 16.6.1
Listing 19.21 Redirecting in the ProductsController.cs file in the Controllers folder
using Microsoft.AspNetCore.Mvc;
using WebApp.Models;
namespace WebApp.Controllers {
[Route("api/[controller]")]
public class ProductsController : ControllerBase {
private DataContext context;
public ProductsController(DataContext ctx) {
context = ctx;
}
// ...other action methods omitted for brevity...
[HttpGet("redirect")]
public IActionResult Redirect() {
return Redirect("/api/products/1");
}
}
}
The controller listing shows a GET action returning a temporary redirect to a product URL. section 19.5.3

