webStuff
webStuff

Reputation: 1494

Routing issue with complex segments

My application performs a search of items by location. I have a few custom routes and redirect rules to provide a nice and friendly URL to the user but I just noticed a strange behaviour with some of them.

My route is defined as follow:

routes.MapRoute("searchRoute", "search/in-{location}", new { controller = "search", action = "index" });

The following searches work very well:

The complex pattern I use here is "search/in-{location}". I also format the location by replacing any white space characters by a '-' with some redirects elsewhere (but it is not relevant here).. The problem happens when the search URL has a location that contains "in-":

For instance, the URLs /search/in-darwin-city or /search/in-testin-test are not matched by my searchRoute (I used RouteDebugger to confirm it and even tested other keyword than 'in-' without luck).

Microsoft doc (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-2.2#complex-segments) says:

Complex segments (for example [Route("/x{token}y")]) are processed by matching up literals from right to left in a non-greedy way.

I had a look at the code (https://github.com/aspnet/AspNetCore/blob/release/2.2/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs#L293) but still not sure why this is happening and most importantly how to solve that.

Any help would be much appreciated

Upvotes: 0

Views: 294

Answers (1)

unite perry
unite perry

Reputation: 15

it won't match because the matching process confuses the position of the literal content with the first part of the content that should be assigned to the location variable since the matching is done from right to left. so let's say your URL is "/search/in-darwin-city". what is at the end? "in-city" so the location variable is assumed to be equal to "city" but what remains is "search/in-darw" which is not equal to "search/" so it's not a match.

if you do something like this: "/search/in-darwincity" and set the route to "/search/in-{location}" then the location variable is going to be "darwincity" and everything works.

Upvotes: 1

Related Questions