I know how to create a URL friendly route and i also know how to remove index. But I’m wondering how do I combine the two together?
Using this tutorial https://www.jerriepelser.com/blog/generate-seo-friendly-urls-aspnet-mvc/ I was able to add the following code to allow for url friendly routes.
routes.Add("ProductDetails", new SeoFriendlyRoute("drink/{id}",
new RouteValueDictionary(new { controller = "Drink", action = "Index" }),
new MvcRouteHandler()));
So instead of my url being test.com/index/drink/1
it now becomes test.com/index/drink/coke
The next set of code I have is to remove the index from the url.
routes.MapRoute("DrinkRoute",
"drink/{id}",
new { controller = "Drink", action = "Index" });
This will succesfully convert test.com/index/drink/1
to test.com/drink/1
May I ask how do I combine the two together so that I can have a route that will lead me to the correct controller action and display test.com/drink/coke
RouteConfig
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
3
Answers
If I understand you correctly, you can achieve desired behavior with
RouteConfig.cs
:In that case the url
test.com/drink/coke
will be hit with the controllerDrinkController.cs
and the action methodIndex
. Id will becoke
. Source code of this controller:You can also achieve the same using attribute routing which would provide more control of the desired routes.
Reference Attribute Routing in ASP.NET MVC 5
First you would need to enable attribute routing by calling
routes.MapMvcAttributeRoutes();
in yourRouteConfig
. Make sure it is registered before convention-based routes.With attribute routing enabled you can specify your routes by annotating your actions and controllers.
The above
DrinkController.Index
action is now mapped toGET drink/coke
assumingtest.com
is the host of the controller as shown in your example.Any controllers or actions not annotated by routing attributes will default back to the convention based routes (if any) registered in the routing table.
This means that you can have a mix of convention-based and attribute-based routes defined for your controllers.
Note however that once you use the attribute routes on a controller that you will have to use it on all its public actions.
You can remove the SEO Routes and give your action or controller full control: