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:

MethodDescription
MapGetMaps a GET request to a RequestDelegate .
MapPostMaps a POST request to a RequestDelegate .
MapPutMaps a PUT request to a RequestDelegate .
MapDeleteMaps a DELETE request to a RequestDelegate .
MapMethodsMaps a route pattern and multiple HTTP methods to a RequestDelegate .
MapMaps a route pattern to a RequestDelegate .
MapFallbackMaps a fallback RequestDelegate which runs when no other routes match.
MapGroupAllows configuring a route pattern and properties that apply to all endpoints defined under that group.

 Table 5.1: Map route-to-delegate extension methods.

Here’s a minimal GET example:

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:

GET!

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.

Next, we explore ways to configure endpoints so we can create better APIs than an endpoint returning a literal string.

Configuring endpoints

Now that we know that with minimal APIs, we map routes to delegates and that we have learned of a few methods to do that, let’s explore how to register the delegates:

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.

You may also like