简体   繁体   中英

MVC 4 URL routing to absorb old legacy urls and forward to new domain

My domain used to point to a wordpress site where I had set up specific pages using the following format:

www.mydomain.com/product/awesome-thing
www.mydomain.com/product/another-thing

Recently I transferred my domain and now it points to an MVC version of my site. The links mentioned above are no longer valid, however the wordpress site still exists with a different domain. I'm trying to get my mvc site to absorb the previous links and forward them to

http://mydomain.wordpress.com/product/awesome-thing 
http://mydomain.wordpress.com/product/another-thing

what I have right now is the following in the RouteConfig.cs

routes.MapRoute(
            name: "product",
            url: "product/{id}",
            defaults: new { controller = "product", action = "redirect", id = UrlParameter.Optional });

and in my product controller I have the following

public void redirect(string id)
{
   if (id == "awesome-thing")
        {
            Response.Redirect("http://mydomain.wordpress.com/product/awesome-thing ");
        }
        if (id == "another-thing")
        {
            Response.Redirect("http://mydomain.wordpress.com/product/another-thing");
        }
        Response.Redirect(" http://mydomain.wordpress.com/");
}

However my routing in RouteConfig.cs is not linking up correctly with my controller. I keep getting "404 The resource cannot be found" error.

I managed to solve this issue by reordering my map routes. I also changed the code in the controller and the maproute a bit, the following code ended up working.

routes.MapRoute(
          name: "productAwesome",
          url: "product/awesome-thing",
          defaults: new { controller = "product", action = "redirectAwsome" });

routes.MapRoute(
         name: "productAnother",
         url: "product/another-thing",
         defaults: new { controller = "product", action = "redirectAnother" });

//it's important to have the overriding routes before the default definition. 
routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

then in the product controller I added the following:

public class productController : Controller
{

    public void redirectAwsome()
    {
        Response.Redirect("http://mydomain.wordpress.com/product/awesome-thing ");
    }
    public void redirectAnother()
    {
        Response.Redirect("http://mydomain.wordpress.com/product/another-thing");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM