Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect with ASP.NET MVC MapRoute

On my site, I have moved some images from one folder to another.

Now, when I receive a request for old images '/old_folder/images/*' I want to make a permanent redirect to new folder with these images '/new_folder/images/*'

For example:

/old_folder/images/image1.png => /new_folder/images/image1.png

/old_folder/images/image2.jpg => /new_folder/images/image2.jpg

I have added a simple redirect controller

public class RedirectController : Controller
{
    public ActionResult Index(string path)
    {
        return RedirectPermanent(path);
    }
}

Now I need to setup proper routing, but I don't know how to pass the path part to the path parameter.

routes.MapRoute("ImagesFix", "/old_folder/images/{*pathInfo}", new { controller = "Redirect", action = "Index", path="/upload/images/????" }); 

Thanks

like image 830
Khachatur Avatar asked Jan 18 '14 05:01

Khachatur


2 Answers

I would do in next way

routes.MapRoute("ImagesFix", "/old_folder/images/{path}", new { controller = "Redirect", action = "Index" }); 

and in controller like that

public class RedirectController : Controller
{
    public ActionResult Index(string path)
    {
        return RedirectPermanent("/upload/images/" + path);
    }
}
like image 87
Vova Bilyachat Avatar answered Sep 19 '22 15:09

Vova Bilyachat


Answer above using RouteMagic is a good idea, but the example code is wrong (it's included in Phil's post as a bad example).

From the RouteMagic Github demo site 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" });

If you specify two routes, you will be setting up an extra mapping that will catch URLs which you don't want.

like image 35
Matt Kemp Avatar answered Sep 17 '22 15:09

Matt Kemp