Creating a route template that matches all urls that starts with a specific pattern in ASP.NET Core

1.1k Views Asked by At

I have an application that is written on the top of ASP.NET Core 5 / .NET 5 Framework. I need to create a route template that would direct any URL that starts with /homes-for-sale-in-{city}-{id:int} to define controller/action.

Here are some examples of urls

/homes-for-sale-in-los-angeles-100/condo,apartment_type
/homes-for-sale-in-los-angeles-100/0-5000_price/10_page
/homes-for-sale-in-los-angeles-100/condo_type/0-5000_price/2_page
.... yes there are many more

I tried the following pattern

[Route("/homes-for-sale-in-{city}-{id:int}{*.}", Name = "HomesForSaleByCity")]
public async Task<IActionResult> Display(string city, id? id)
{
    return View();
}

But I get this error:

RoutePatternException: A path segment that contains more than one section, such as a literal section or a parameter, cannot contain a catch-all parameter.

How can I add a pattern that would redirect any url that would starts with a pattern?

2

There are 2 best solutions below

0
On BEST ANSWER

This did the trick

[Route("/homes-for-sale-in-{city}-{id:int}/{**filters}", Name = "HomesForSaleByCity")]
public async Task<IActionResult> Display(string city, id? id, string filters = "")
{
    return View();
}
1
On

I believe you need to use regex for your routing, and may refer this page once.