Map route-to-delegate – Minimal API
How does it work? Minimal APIs bring multiple extension methods to configure the HTTP pipeline and configure endpoints. We can use those methods to map a route (a URL pattern) to a RequestDelegate delegate.We can use the following methods to map different HTTP methods:
Method | Description |
MapGet | Maps a GET request to a RequestDelegate . |
MapPost | Maps a POST request to a RequestDelegate . |
MapPut | Maps a PUT request to a RequestDelegate . |
MapDelete | Maps a DELETE request to a RequestDelegate . |
MapMethods | Maps a route pattern and multiple HTTP methods to a RequestDelegate . |
Map | Maps a route pattern to a RequestDelegate . |
MapFallback | Maps a fallback RequestDelegate which runs when no other routes match. |
MapGroup | Allows configuring a route pattern and properties that apply to all endpoints defined under that group. |
Table 5.1: Map route-to-delegate extension methods.
app.MapGet(“minimal-endpoint-inline”, () => “GET!”);
When executing the program, navigating to the /minimal-endpoint-inline URI routes the request to the registered RequestDelegate (highlighted code), which outputs the following string:
As simple as that, we can route requests to delegates and create endpoints.
On top of registering endpoints, we can also register middleware like any other ASP.NET Core application. Moreover, the built-in middlewares, like authentication and CORS, work the same with Minimal APIs.
To declare the delegate inline, we can do the following:
app.MapGet(“minimal-endpoint-inline”, () => “GET!”);
To use a method, we can do the following:
app.MapGet(“minimal-endpoint-method”, MyMethod);
void MyMethod() { }
When enabled, ASP.NET Core registers the class name that contains the method with the ApiExplorer as a tag. We dig deeper into metadata further in the chapter.
All the concepts we explore in this chapter apply to both ways of registering delegates. Let’s start by studying how to input data in our endpoints.