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
You can use Attribute routing and decorate those action methods with the pattern you want.
In order to use Attribute Routing it must be enabled by calling
MapMvcAttributeRoutes
in your RouteConfig: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 inRouteConfig.cs
With the traditional routing approach, your old
(youtSite/home/about
) and new route pattern (yourSite/about
) will work. If you want onlyyourSite/about
, I suggest you go the Attribute routing approach.you can use attribute routing of MVC5. To enable Attribute Routing, write below line in RouteConfig.cs
and then your Homecontroller’s Action method like this
to know more about MVC5 Attribute Routing