在我的网站上,我已将一些图像从一个文件夹移动到另一个文件夹。
现在,当我收到旧图像请求'/ old_folder / images / *'时,我想永久重定向到这些图像的新文件夹'/ new_folder / images / *'
例如:
/old_folder/images/image1.png => /new_folder/images/image1.png
/old_folder/images/image2.jpg => /new_folder/images/image2.jpg
我添加了一个简单的重定向控制器
public class RedirectController : Controller
{
public ActionResult Index(string path)
{
return RedirectPermanent(path);
}
}
现在我需要设置正确的路由,但我不知道如何将路径部分传递给路径参数。
routes.MapRoute("ImagesFix", "/old_folder/images/{*pathInfo}", new { controller = "Redirect", action = "Index", path="/upload/images/????" });
由于
答案 0 :(得分:23)
我会以下一个方式做的
routes.MapRoute("ImagesFix", "/old_folder/images/{path}", new { controller = "Redirect", action = "Index" });
并在控制器中
public class RedirectController : Controller
{
public ActionResult Index(string path)
{
return RedirectPermanent("/upload/images/" + path);
}
}
答案 1 :(得分:7)
首先从this link下载并安装RouteMagic包,然后将旧地址重定向到新地址如下代码:
var NewPath = routes.MapRoute("new", "new_folder/images/{controller}/{action}");
var OldPath = routes.MapRoute("new", "old_folder/images/{controller}/{action}");
routes.Redirect(OldPath ).To(NewPath );
了解更多信息,请查看以下链接 Redirecting Routes To Maintain Persistent URLs
答案 2 :(得分:1)
上面使用RouteMagic的答案是个好主意,但是示例代码是错误的(它作为 bad 示例包含在Phil的帖子中)。
从RouteMagic Github演示站点global.asax.cs:
// Redirect From Old Route to New route
var targetRoute = routes.Map("target", "yo/{id}/{action}", new { controller = "Home" });
routes.Redirect(r => r.MapRoute("legacy", "foo/{id}/baz/{action}")).To(targetRoute, new { id = "123", action = "index" });
如果您指定两条路线,则将设置一个额外的映射,以捕获不需要的URL。