end point not working in .netcore 2.1, why?

Viewed 118

This is a very simple question about why is this happening.

First of all, I've got a .net core 2.1 project, and I need 3 extra endpoints, so this is my code:

        app.Map("/h1", handle1);
        app.Map("/h1/h2", handle2);
        app.Map("/h1/h3", handle3);

in the Configure method. handle1, handl2 and handle3 are custom methods to write different things on localhost:port/h1, localhost:port/h1/h2 and localhost:port/h1/h3.

However this is not working, because I get at localhost:port/h1/h2 the same result than for the other two, so localhost:port/h1 is correct but localhost:port/h1/h2 and localhost:port/h1/h3 are showing localhost:port/h1 which is not correct.

I have tried a few things, and this is kind of working:

    app.Map("/h1", handle1);
    app.Map("/h/h2", handle2);
    app.Map("/h/h3", handle3);

questions are why? and how do I make it so localhost:port/h1 and localhost:port/h1/h2 and localhost:port/h1/h3 work?

Update:

I tried this and it works, but I don't get why

    app.Map("/h1/h2", handle2);
    app.Map("/h1/h3", handle3);
    app.Map("/h1", handle1);
1 Answers

It's the order of checking that's important.

Say your url is:

url = "/h1/h2/somethingcool"

The way your map is built up is:

[ 
  "/h1"
  "/h1/h2",
  "/h1/h3"
]

So when your map is looped this happens(pseudocode):

for(map.entries() : entry) {
    if(url.startsWith(entry.url) {
       entry.doTheThing(url);
       break;
    }
}

so when we patch values in there:

url = "/h1/h2/somethingcool"
foreach value in [ "/h1", "/h1/h2", "/h1/h3" ] put it in entry
loop 1:
   entry = "/h1"
   if([url]"/h1/h2/somethingcool" starts with [entry]"/h1") 
     do the route
     abort looping 
Loop is aborted
stopping processing other array items.

Now if we take your other map that does work, we get the behaviour we expect.

url = "/h1/h2/somethingcool"
foreach value in [ "/h1/h3", "/h1/h2", "/h1" ] put it in entry
loop 1:
   entry = "/h1/h3"
   if([url]"/h1/h2/somethingcool" starts with [entry]"/h1/h3") 
     it did not match. Continue looping.
   if([url]"/h1/h2/somethingcool" starts with [entry]"/h1/h2") 
     do the route
     abort looping 
Loop is aborted
stopping processing other array items. 

I hope this helps you understand the logic behind the process. It all boils down to that the url is matched if it starts with it, not if it's a perfect match.

Related