在MVC中重定向来自旧网站的请求

本文关键字:网站 请求 MVC 重定向 | 更新日期: 2023-09-27 18:07:54

我用ASP为客户建立了一个网站。. Net MVC 3,这是为了取代我没有建立的旧网站,是用PHP编写的。

我在新网站上的大多数页面都是从原来的旧网站映射到旧网站,例如www.mysite.com/contactus以前是www.mysite.com/contactus.php

在检查了我的错误日志(由Elmah记录)之后,我得到了一些旧页面请求的错误,像这样:

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

有没有人有关于如何纠正这个问题的建议,理想情况下,将用户重定向到新的目的地,如果它存在,或者只是默认它们到主页。

在MVC中重定向来自旧网站的请求

您应该能够在web.config中使用IIS重写规则:

<rewrite>
  <rules>
    <rule name="Remove .php suffix">
      <match url="^(.*).php$" />
      <action type="Rewrite" url="{R:1}" />
    </rule>
  </rules>
</rewrite>

这将在任何传入请求上删除'.php'后缀。查看更多信息:http://www.iis.net/learn/extensions/url-rewrite-module/creating-rewrite-rules-for-the-url-rewrite-module

您可以使用以下路由:

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);
        }
    }
}