crowz crowz - 3 months ago 19
ASP.NET (C#) Question

urls like "home.asp" redirect in mvc

I need to rebuild a website (in old they use classic ASP but they want to make it now MVC 4) and they dont want to change the urls. for example if the search screen's url is blabla.com/search.asp they want to keep it like this. But mvc doesn't allow to make urls like "search.asp". I want to keep url like this but render search View. Am I need to do this all one by one or there is a dynamic way for it?

for example

requested url = "blabla.com/string variable"
if variable.Substring(variable.Length - 4) == ".asp";
return View("variable.Substring(0, (variable.Length - 4))")


Note: Syntax is all wrong, I know. I just tried to explain the condition..

Note2: They want this because of "SEO" things. they don't want to lose their ratings. any method that doesn't change anything for google, they will accept that method I guess.

Answer

You need two things.

  1. Define a route for *.asp
  2. Add an handler for *.asp

RouteConfig

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "DefaultAsp",
        url: "{controller}/{action}.asp/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Handler (WebConfig)

(This one needs to be inserted inside /system.webServer/handlers

  <add name="AspFileHandler" path="*.asp" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

Doing this you are also making all URL's built with MVC available with .asp, that means that if you have an anchor that calls another View, that view will have the normal mvc URL with .asp suffix.

Note

This is generic, you only need to add this line once. Home/Index displayed are just the default Controller and Action.

Note 2

Forgot to explain the handler.

You need it because IIS thinks you are asking for an ASP file an it'll try to reach that page and return an error since it doesn't exist.

With this handler you are allowing your application to handle those pages itself.