how to Map multiple .net core controller routes

77 views Asked by At

I currently map my controller routes like this:

var webApplication = builder.Build();
webApplication.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");

This works great for my default scenario where I don't provide action name or id in the parameters. So for example the following routes work:

https://example.com.com
https://example.com.com/Home
https://example.com.com/Books
https://example.com.com/Books/Show/1

However, I am moving to SEO more friendly names for some of the products and instead of /1 I want to have /my-book-name. However, I still want the old way to behave the same. I just want to be able to type now:

https://example.com.com/Books/Show/my-book-name

I do not wish to have to do this on every action method individually, so I tried the following:

var webApplication = builder.Build();
webApplication.MapControllerRoute("default-uri", "{controller}/Show/{uri}");
webApplication.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");

However, the above does not work when I enter

https://example.com.com/Books/Show/my-book-name

How can I achieve the above? I am using .NET Core 8

1

There are 1 answers

0
akg179 On

In the route configuration that you created for the scenario of '/my-book-name', you can add a third parameter of 'constraints' and specify a regular expression that allows any word with dashes for 'uri' route parameter.

So the updated route configuration will look something like this-

webApplication.MapControllerRoute("default-uri", "{controller}/Show/{uri}", constraints: new { uri = @"[\w\-]+" });