On ASP.net MVC, what is the "correct" way to have a controller return a 301 Redirect to an external site?
The various RedirectTo-Function seem to only return either relative links or routes that i have mapped manually, but there is no way to say "Perform a 301 Redirect to http://example.com".
I think I could just set Response.StatusCode or use Response.Redirect, but is that the way it should be done in MVC? Or is there an official "correct way" of performing redirects?
Update: In the meantime, I wrote an ActionResult for that: PermanentRedirectResult
Update 2: Since ASP.net 4.0, Permanent Redirects are part of the Framework.
Can You Reverse A 301 Redirect? The short answer is "yes." You can reverse a 301-redirect, even though it's technically permanent. The long answer, though, is that this change may not work the way you'd expect or hope, and it could even make your problems worse.
If the source of most of your traffic comes from search engine results, then you can just shut down your 301 redirects after a few months to a year. Like Mueller said, this would be enough time for Google to track your move and recognize your new site.
The 301 and 308 status codes mean that a page has permanently moved to a new location.
Use
Response.RedirectPermanent("http://www.google.com");
or for returning an ActionResult type from a controller:
return RedirectPermanent("http://www.google.com");
provided by the ASP.net 4.0 framework.
Since you are talking about redirecting to a URL that you do not know anything about the routing (be that an internal page (think classic ASP.NET), or some external resource) then the only thing you can do is set the status code, and send the user's browser on its way.
At this chain in MVC you are worried about getting the user to their View, but that View is not under your control and may not even be a View at all. So ultimately you are doing this best you can in this circumstance, and to my knowledge are not breaking any MVC "rule".
I hope that helps.
I perform redirects to support legacy URLs.
My controller looks something like this…
Public Class ThingController
Inherits System.Web.Mvc.Controller
Function Details(ByVal id As String) As ActionResult
Dim RedirectId As Guid
Select Case key
Case "legacyurlone"
RedirectId = New Guid("c564c0c1-c365-4b0c-bc33-fd4eadf0551b")
Case "legacyurltwo"
RedirectId = New Guid("157fa15b-8d5d-4f04-87cc-434f7ae93dfa")
Case Else
RedirectId = Guid.Empty
End Select
If Not RedirectId = Guid.Empty Then
Response.StatusCode = Net.HttpStatusCode.MovedPermanently
Response.RedirectLocation = Url.RouteUrl("IdOnly", New With {.id = RedirectId})
Return Nothing
End If
Dim ThingId As Guid = New Guid(id)
Dim db As New ThingEntities
Dim Model As Thing = ...
Return View(Model)
End Function
...
End Class
I now wonder if I could handle this more cleanly with two routes and controller functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With