Inputs – Minimal API
An endpoint rarely has no parameter (no input value). Minimal APIs, like MVC, support a wide variety of binding sources. A binding source represents the conversion from the HTTP request into a strongly typed C# object, inputted as a parameter. Most of the parameter binding happens implicitly, but in case you need to bind a parameter explicitly, here are the supported binding sources:
Table 5.2: supported binding sources
Next is a demo where we implicitly bind the id parameter from the route (highlighted code) to a parameter in the delegate:
app.MapGet(
“minimal-endpoint-input-route-implicit/{id}”,
(int id) => $”The id was {id}.”
);
In most cases, the bindings work implicitly. However, you can explicitly bind the delegate’s parameters like this:
app.MapGet(
“minimal-endpoint-input-route-explicit/{id}”,
([FromRoute] int id) => $”The id was {id}.”
);
app.MapGet(
“minimal-endpoint-input-service/{value}”,
(string value, SomeInternalService service)
=> service.Respond(value)
);
public class SomeInternalService {
public string Respond(string value)
=> $”The value was {value}”;
}
Following this pattern opens endless possibilities to input data into our endpoints.
If you are unfamiliar with Dependency Injection (DI), we explore DI more in-depth in Chapter 8, Dependency Injection. Meanwhile, remember that we can bind objects to parameters, whether they are a DTO or a service.
On top of that, ASP.NET Core provides us with a few special types, which we explore next.
Here’s an example where two endpoints write to the response stream, one using the HttpContext and the other the HttpResponse object:
app.MapGet(
“minimal-endpoint-input-HttpContext/”,
(HttpContext context)
=> context.Response.WriteAsync(“HttpContext!”)
);
app.MapGet(
“minimal-endpoint-input-HttpResponse/”,
(HttpResponse response)
=> response.WriteAsync(“HttpResponse!”)
);