Url.Action 生成旧路线与新路线

Url.Action generates old route vs new route

在ASP.NETMVC路由中,如果要支持遗留路由,可以这样添加:

routes.MapRoute("SiteDefault", "Default.aspx",  
    new { controller = "Home", action = "Index" });

太好了,但是当我使用 @Url.Action 为家庭控制器索引操作生成 link 时,如下所示:

<a href="@Url.Action("Index", "Home")">Home</a>

Url 生成的是 /Default.aspx 而不是 /Home.

如何让助手生成 /Home 并仍然支持 /Default.aspx 的路由映射?

我知道我可以创建物理 [​​=18=] 文件并在其中进行永久重定向,但我正在努力避免添加不必要的文件。

或者有没有一种方法可以为 UrlHelper 编写扩展来做到这一点?

可以通过创建仅匹配传入请求的路由约束来解决此问题。

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 (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.