ASP.NET MVC MapRoute中的重定向

13

我在网站上将一些图片从一个文件夹移动到另一个文件夹。

现在,当我收到针对旧图片'/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/????" }); 

谢谢

3个回答

29

我会以下列方式进行

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

6

首先从此链接下载并安装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 );

欲了解更多信息,请查看以下链接:重定向路由以保持持久URL


你应该将这个作为评论发布 - web-tiki
如果您阅读“了解更多信息”的链接,您会发现Phil明确表示您不能仅传递两个路由到Redirect - 您必须使用lambda表达式,我将在单独的答案中提供详细信息。 - Matt Kemp

2
使用RouteMagic来回答上面的问题是一个好主意,但是示例代码是错误的(它被包含在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。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接