2013-04-06 40 views
3

我已经为使用ASP.Net MVC 3的客户端构建了一个网站,该网站用于替换我未构建并使用PHP编写的旧网站。在MVC中重定向来自旧网站的请求

大多数使用我有新的网站地图上一个老从原来的页面,如www.mysite.com/contactus的是www.mysite.com/contactus.php

审查后我的错误日志(由Elmah记录)我收到了一些旧页面的请求错误,如下所示:

路径'/ContactUs.php'的控制器未找到或未实现IController。

有没有人有关于如何解决此问题的建议,理想情况下是将用户重定向到新的目的地(如果它存在或只是将其默认为主页)。

回答

2

你可以使用这条路线:

routes.MapRoute(
    name: "oldphp", 
    url: "{*path}", 
    defaults: new { controller = "PhpRedirect", action="Get" }, 
    constraints: new { path = @".*\.php" }); 

,然后实现PhpRedirectController这样的:

public class PhpRedirectController : Controller 
{ 
    [HttpGet] 
    public ActionResult Get(string path) 
    { 
     // TryGetNewUrl should be implemented to perform the 
     // mapping, or return null is there is none. 
     string newUrl = TryGetNewUrl(path); 
     if (newUrl == null) 
     { 
      // 404 not found 
      return new HttpNotFoundResult(); 
     } 
     else 
     { 
      // 301 moved permanently 
      return RedirectPermanent(newUrl); 
     } 
    } 
} 
+0

将这项工作包含子目录的网址? – 2013-04-06 20:29:17

+0

@AntP:我已经更新了我的答案,以便它在那种情况下也能正常工作。 – 2013-04-06 21:17:32