4

I'm using ASP.NET Core to serve an SPA like this:

[<Route("{*url}")>]
member this.Index () =      
    this.View("~/wwwroot/Index.cshtml")

My JSON endpoints are on the same app, routed like this:

[<Route("api/something/{somethingId:int})>]

This works fine, except that when I try to call an endpoint api/something/that/doesnt/exist I get the index page when I actually want a 404.

Is it possible to setup [<Route("{*url}")>] in such a way that it excludes any url that starts with "api"?

1

1 Answer 1

13

You should use Route Constraints. There is a regex option which you can use to filter out the API calls (That you don't want).

You then need to do a negative lookahead to negate a string.

[<Route("{*url:regex(^(?!api).*$)}")>]
Sign up to request clarification or add additional context in comments.

1 Comment

This approach did the trick for me! I had to handle a fixed set of known folder names as well as a set of file extensions and so wound up with this: {*url::regex(^(?!.*(?:(?:data|images|css)|(?:\\.tsx|\\.ts|\\.mjs|\\.js)$)).*$)} . I tried for a long time to include the forward slashes into the folder pattern (i.e. /images/ instead of just images) but could never get it to work, so this regex just matches the sequence of characters in any part of the route. Somehow the routing engine in ASP.NET Core didn't seem to recognize the escape sequences \\/ that worked well in regex101.com.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.