In ASP.NET MVC routing, if you want to support legacy routes, you can add something like this:
routes.MapRoute("SiteDefault", "Default.aspx",
new { controller = "Home", action = "Index" });
That's great, but when I use @Url.Action
to generate link for Home controller Index action as following:
<a href="@Url.Action("Index", "Home")">Home</a>
Url generated is /Default.aspx
and not /Home
.
How can I get helper to generate /Home
and still support route mapping for /Default.aspx
?
I know that I can create physical Default.aspx
file and have permanent redirect inside it, but I am trying to avoid adding unnecessary files.
Or is there a way to write Extension for UrlHelper
that would do this?
You could fix this by creating a route constraint that only matches incoming requests.
public class IncomingOnlyConstraint : IRouteConstraint
{
public bool Match(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection)
{
return routeDirection == RouteDirection.IncomingRequest;
}
}
routes.MapRoute("SiteDefault", "Default.aspx",
new { controller = "Home", action = "Index" },
new { controller = new IncomingOnlyConstraint() });
NOTE: The above solution is not the best one. It is generally bad for SEO to have more than one URL serving the same content. If you use the above solution, you should ensure your response has a canonical tag or header set.
A far better solution would be to do a 301 redirect from the old URL to the new URL. You could either handle that directly through MVC (which will ensure all browsers that don't respect the 301 response have a better user experience), or you can use the IIS URL rewrite module to issue the 301 redirect, which keeps the legacy code neatly outside of your application.