'How can I configure a (.net6) WebApplication with a handler for all GET requests that don't have a MapGet?

I have a WebApplication running inside a console app with various MapGet handlers configured.

var app = WebApplication.Create();
app.MapGet("/", GetHome);
/* Other MapGet calls and handlers removed for brevity. */
app.Run();

Because this would be replacing an established website, I would like to specify a custom handler for any GET request that doesn't have its own MapGet instead of the normal 404 response.

Is there a way I can specify a GET handler of last resort? (One that allows any number of slash-separated folders and any or no file extension on the end.)



Solution 1:[1]

With a bit of experimentation, this seemed to work, if more by accident than design.

app.MapGet("/{**x}", MyHandler);

The double-asterisk appears to indicate multiple folders are allowed. The "x" is there because MapGet will only accept the string if the part has a name. If MyHandler has an HttpContext parameter, the URL is available in the context.Request.Path property.

I hope someone has a better answer to this. It feels there should be a Map call that simply says "All unmapped requests go here".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 billpg