Khachatur
Khachatur

Reputation: 989

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

Upvotes: 14

Views: 35085

Answers (3)

Matt Kemp
Matt Kemp

Reputation: 2920

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.

Upvotes: 2

J_hajian_nzd
J_hajian_nzd

Reputation: 185

first download and install RouteMagic package from this link , then redirect your old address to the new address Like the below code :

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

for more information please check out the following link Redirecting Routes To Maintain Persistent URLs

Upvotes: 6

Vova Bilyachat
Vova Bilyachat

Reputation: 19474

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

Upvotes: 29

Related Questions