IIS throws 404 errors outside of my ASP.NET MVC application

I have replaced the old PHP website with the new ASP.NET MVC website. Old page addresses no longer work. I want each of the 301s (moving constantly) to be redirected to specific new addresses.

But IIS 7 seems to intercept many of these requests before they reach my application. I want to handle error logging and redirects in the Application_Error () method of my Global.asax file, instead of having IIS serve up generic error pages.

How do I change IIS to allow this?

+1


a source to share


1 answer


I think MVC doesn't consider this to be an error (i.e. not throwing an exception), but rather just doesn't match any of the routes and so IIS handles 404s as usual. To handle this in code, I would add a wildcard pattern at the end of your routing list.

Global.asax.vb & hellip;

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

      

FileNotFoundController.vb & hellip;



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 allow you to view the intended URL and decide which target URL to redirect to.

Alternatively, you can implement a custom 404 handler page and install it directly in IIS. In the code of that page / controller, you can view the intended url and redirect as needed.

+1


a source







All Articles