skip to Main Content

I have an asp.net MVC 5 site.

I have many routes – eg

http://example.com/places/placename
http://example.com/home/about
http://example.com/home/privacy

The first is dynamic – the latter two just point to the about & privacy actions in the home controller.

This works fine, however, I would like all ‘/home/’ URLs to point to the root. eg

http://example.com/home/privacy

Should point to

http://example.com/privacy

I would also like the old route to no longer work (duplication of content is bad for SEO).

The former is easy enough to do but the old route still works. What is an elegant way to handle this?

thx.

2

Answers


  1. You can use Attribute routing and decorate those action methods with the pattern you want.

    public class HomeController : Controller
    {
       [Route("privacy")]
       public ActionResult Privacy()
       {
          return view();
       }
       [Route("about")]
       public ActionResult About()
       {
          return view();
       }
    }
    

    In order to use Attribute Routing it must be enabled by calling MapMvcAttributeRoutes in your RouteConfig:

    routes.MapMvcAttributeRoutes();
    

    Another option is to specify a route definition before registering the default route definition(the order matters.So specific route definition should be registered before the catch-rest default route definition) in your RouteConfig (Traditional routing approach)

    So add a specific route definition in your RegisterRoutes method in RouteConfig.cs

    //register route for about
    routes.MapRoute( "about", "about",
            new { controller = "Home", action = "about" });
    
    routes.MapRoute("Default", "{controller}/{action}/{id}",
             new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    

    With the traditional routing approach, your old (youtSite/home/about) and new route pattern (yourSite/about) will work. If you want only yourSite/about, I suggest you go the Attribute routing approach.

    Login or Signup to reply.
  2. you can use attribute routing of MVC5. To enable Attribute Routing, write below line in RouteConfig.cs

    routes.MapMvcAttributeRoutes(); // Add this line
    

    and then your Homecontroller’s Action method like this

    [Route("privacy")]
    public ActionResult Privacy()
    {
       return view();
    }
    

    to know more about MVC5 Attribute Routing

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search