Home > database >  Map wildcard in .NET Core WebApplication
Map wildcard in .NET Core WebApplication

Time:01-04

How can I create the request mapping so that all requests GET, POST, PUT, ... and all paths execute the same method.

var application = WebApplication.Create();
application.Map("/", () =>
{
    return "This is all I do!";
});
application.Run("http://localhost:8080");

My guess is that there is a wildcard pattern that will work, but i have tried the following without success: "/", "*", "/*" and "/**".

CodePudding user response:

You can use application.Run with the RequestDelegate parameter instead of Map, to handle any and all requests:

public static void Main()
{
    var application = WebApplication.Create();
    
    application.Run(async context =>
    {
        await context.Response.WriteAsync("This is all I do!");
    });

    application.Run("http://localhost:8080");
}

CodePudding user response:

See the Wildcard and catch all routes section of the docs:

app.Map("/{*rest}", (string rest) => rest);

Or you can use "catch all" middleware:

app.Use(async (HttpContext ctx, Func<Task> _) =>
{
    await ctx.Response.WriteAsync("Hello World!");
});
  • Related