威廉,
我在一个旧的 mvc 1 网站上有一个类似的场景。但是,逻辑可能仍然合适。我有许多已知页面和各种未知页面要处理。当时,我在行动中使用了一种相当笨拙的方法来处理它,如下所述:
public ActionResult Index()
{
string routeval = (string)this.RouteData.Values["file"];
var dicT = new Dictionary<string, int>();
// oh deary me - hardcoded values
dicT.Add("algarve", 1);
dicT.Add("brazil", 5);
dicT.Add("colorado", 4);
dicT.Add("morocco", 2);
dicT.Add("thailand", 6);
// what, no test for culture/case :-)
if (dicT.ContainsKey(routeval))
{
var routeData = new RouteValueDictionary(
new
{
controller = "Property",
action = "Details",
id = dicT[routeval],
Lang = "en"
});
return RedirectToAction("Details", "Property", routeData);
}
else
{
return View();
}
}
[编辑] - 从那个旧的 mvc1 应用程序中找到另一个“有用”的信息。您可以将以下内容添加到基本控制器:
public class LegacyUrlRoute : RouteBase
{
// source: http://www.mikesdotnetting.com/Article/108/Handling-Legacy-URLs-with-ASP.NET-MVC
public override RouteData GetRouteData(HttpContextBase httpContext)
{
const string status = "301 Moved Permanently";
var request = httpContext.Request;
var response = httpContext.Response;
var legacyUrl = request.Url.ToString();
var newUrl = "";
if (legacyUrl.Contains("/villas/") || legacyUrl.EndsWith("asp"))
{
if (legacyUrl.Contains("/villas/"))
newUrl = "/en/home/Destinations";
else if (legacyUrl.EndsWith("asp"))
{
newUrl = "/en/home/index";
if (legacyUrl.Contains("about"))
newUrl = "/en/home/AboutUs";
if (legacyUrl.Contains("offers"))
newUrl = "/en/home/Offers";
if (legacyUrl.Contains("contact"))
newUrl = "/en/home/ContactUs";
if (legacyUrl.Contains("destinations"))
newUrl = "/en/home/destinations";
if (legacyUrl.Contains("faq"))
newUrl = "/en/home/Faq";
if (legacyUrl.Contains("terms"))
newUrl = "/en/home/Terms";
if (legacyUrl.Contains("privacy"))
newUrl = "/en/home/Privacy";
}
response.Status = status;
response.RedirectLocation = newUrl;
response.End();
}
return null;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
return null;
}
}
然后在您的 global.asax 文件中添加一条新路由:
routes.Add(new LegacyUrlRoute());
基本上,我“知道”我正在寻找一个包含“文件”参数的路由值,类似于www.url.com/somepage.asp?file=algarve 等。(这就是旧的 asp 经典网站的工作方式,我知道目前没有这个)。对于我想要重定向到的“已知”路由,我使用了执行RedirectToAction 的逻辑,其他一切都通过默认的Index() View()。
正如我所说,笨拙而不是我现在(大约 2.5 年后)会怎么做,但这是我“四处飘荡”的一个例子,它确实有效! :D
祝你好运