我一般使用如下方法。首先在顶部附近的 Routeconfig 中,我注册了一个新的 Routebase(称为 LegacyURLRoute):
routes.Add(new LegacyUrlRoute());
一个缩减版如下:
public class LegacyUrlRoute : RouteBase
{
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var request = httpContext.Request;
var response = httpContext.Response;
var legacyUrl = request.Url.ToString().ToLower();
var legacyPath = request.Path.ToString().ToLower();
Tuple<bool, bool, string> result = DervieNewURL(legacyPath);
bool urlMatch = result.Item1;
bool urlMatchGone = result.Item2;
var newUrl = result.Item3;
if (urlMatch)
{//For 301 Moved Permanently
response.Clear();
response.StatusCode = (int)System.Net.HttpStatusCode.MovedPermanently;
response.RedirectLocation = "http://www.example.com" + newUrl;
response.End();
}
else if (urlMatchGone)
{// 410 Gone
response.Clear();
response.StatusCode = (int)System.Net.HttpStatusCode.Gone;
response.End();
}
return null;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
return null;
}
}
上面的 DervieNewURL 然后可以在 DB 中包含查找,但最近在一个项目中,我将它作为 HTMLHelper 使用,它还允许我传入直接来自 DB 列的 URL,然后可以对这些进行解析和酌情更新。
DervieNewURL 的简单示例如下所示,但您显然会在表格中查找,而不是像下面这样硬编码位。
public static Tuple<bool, bool, string> DervieNewURL(string url)
{
/*
return type from this function is as follows:
Tuple<bool1, bool2, string1, string2>
bool1 = indicates if we have a replacement url mapped
bool2 = indicates if we have a url marked as gone (410)
string1 = indicates replacement url
*/
Tuple<bool, bool, string> result = new Tuple<bool, bool, string>(false, false, null);
if (!String.IsNullOrWhiteSpace(url))
{
string newUrl = null;
bool urlMatch = false;
bool urlMatchGone = false;
switch (url.ToLower())
{
case "/badfoldergone/default.aspx": { urlMatchGone = true; } break;
case "/oldfoldertoredirect/default.aspx": { urlMatch = true; newUrl = "/somecontroller/someaction"; } break;
default: { } break;
}
result = new Tuple<bool, bool, string>(urlMatch, urlMatchGone, newUrl);
}
return result;
}
如果您需要通配符匹配,那么我想您可以修改上述内容或将其构建到数据库调用匹配条件中。
通过尽早使用此路由,您可以将旧版 url 重定向到其他路由,然后当请求沿路由表向下级联时触发这些路由。最终你会在你的默认路线结束,类似于:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
如果开发人员有硬编码链接,那么您只需要使用将由这些 url 触发的路由。通过采用上述方法,可以尽早捕获并添加到数据库中的列表中,并在需要时添加适当的 301 Moved 或 410 gone 。