Redirect() vs RedirectPermanent() in ASP.NET MVC
By FoxLearn 12/13/2024 12:43:57 PM 61
The key difference is that RedirectPermanent
sends an HTTP 301 (Moved Permanently) status code, indicating a permanent redirection, while Redirect
sends an HTTP 302 (Found) status code, indicating a temporary redirection.
Use RedirectPermanent
when a resource is permanently relocated and is no longer accessible at its original location. Browsers typically cache the HTTP 301 response and handle future redirects automatically.
Use Redirect
when the resource might still be available at the same URL in the future.
For example:
If a deleted user’s details are requested at /user/{userid}
, redirect to /user/does-not-exist
. Use Redirect
since the original URL might become valid again if the user is restored.
If the user will never be restored, use RedirectPermanent
so the browser automatically redirects to /user/does-not-exist
in future requests. If the user may be restored, use a regular Redirect
.
How to use RedirectPermanent
in a controller action?
public ActionResult OldPage() { // Redirect to a new URL with a permanent 301 redirect status return RedirectPermanent("/new-page"); }
In this example, when a user accesses the OldPage
action, they will be permanently redirected to /new-page
. The browser will also update its cached URL for future requests.
RedirectPermanent
should be used when the resource has permanently moved or will never return to its original location.
- 8 Essential Tips to Protect Your ASP.NET Core Application from Cyber Threats
- 10 Common Mistakes ASP.NET Developers Should Avoid
- How to Upload Files Using C# ASP.NET FileUpload Control
- Implementing Caching in ASP.NET Core
- Building a Custom Request Pipeline with ASP.NET Core Middleware
- How to 301 redirect in ASP.NET
- How to fix 'Authorization in ASP.NET Core' with 401 Unauthorized
- How to create a Toast Notifications in ASP.NET Core