1

I've replaced an old PHP web site with a new ASP.NET MVC web site. The old page addresses no longer work. I want each to 301 (Moved Permanently) redirect to specific new addresses.

But, IIS 7 seems to intercept many such requests before they get to my application. I want to handle the error logging and redirections in the Application_Error() method of my Global.asax file rather than have IIS serve up generic error pages.

How must I modify IIS to allow this?

Zack Peterson
  • 56,055
  • 78
  • 209
  • 280

1 Answers1

1

I think MVC does not see this as an error (i.e. raises no exception), but rather it simply does not match any of the routes, and as such lets IIS handle the 404 as it normally would. To handle this in code I would add a wildcard route at the end of your routing list.

Global.asax.vb…

routes.MapRoute( _
    "FileNotFound", _
    "{*key}", _
    New With {.controller = "FileNotFound", _
              .action = "Http404"} _
)

FileNotFoundController.vb…

Function Http404(ByVal key As String) As ActionResult
    Dim RedirectId As Guid
    Select Case key
        Case "someold/path/andfile.php"
            RedirectId = New Guid("68215c26-0abe-4789-968e-0187683409b6")
        Case Else
            RedirectId = Guid.Empty
    End Select
    If Not RedirectId = Guid.Empty Then
        Response.StatusCode = Net.HttpStatusCode.MovedPermanently
        Response.RedirectLocation = Url.RouteUrl("SomeOtherRoute", New With {.id = RedirectId})
    Else
        Throw New Exception("Unable to resolve route.")
    End If
    Return Nothing
End Function

This will let you look at the intended URL and decide which target URL to redirect it to.

Alternatively, you could implement a custom 404 handler page and set that in IIS directly. In the code of that page/controller you could look at the intended URL and redirect as neccessary.

Zack Peterson
  • 56,055
  • 78
  • 209
  • 280
JonoW
  • 14,029
  • 3
  • 33
  • 31