11 KiB
title | author | description | ms.author | monikerRange | ms.date | uid |
---|---|---|---|---|---|---|
Minimal APIs quick reference | rick-anderson | Provides an overview of minimal APIs in ASP.NET Core | riande | >= aspnetcore-6.0 | 6/23/2023 | fundamentals/minimal-apis |
Minimal APIs quick reference
:::moniker range=">= aspnetcore-7.0"
This document:
- Provides a quick reference for minimal APIs.
- Is intended for experienced developers. For an introduction, see xref:tutorials/min-web-api
The minimal APIs consist of:
[!INCLUDE WebApplication]
ASP.NET Core Middleware
The following table lists some of the middleware frequently used with minimal APIs.
The following sections cover request handling: routing, parameter binding, and responses.
Routing
A configured WebApplication
supports Map{Verb}
and xref:Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions.MapMethods%2A where {Verb}
is a camel-cased HTTP method like Get
, Post
, Put
or Delete
:
The xref:System.Delegate arguments passed to these methods are called "route handlers".
Route Handlers
[!INCLUDE route handling]
Parameter binding
Responses
Route handlers support the following types of return values:
IResult
based - This includesTask<IResult>
andValueTask<IResult>
string
- This includesTask<string>
andValueTask<string>
T
(Any other type) - This includesTask<T>
andValueTask<T>
Return value | Behavior | Content-Type |
---|---|---|
IResult |
The framework calls IResult.ExecuteAsync | Decided by the IResult implementation |
string |
The framework writes the string directly to the response | text/plain |
T (Any other type) |
The framework JSON-serializes the response | application/json |
For a more in-depth guide to route handler return values see xref:fundamentals/minimal-apis/responses
Example return values
string return values
app.MapGet("/hello", () => "Hello World");
JSON return values
app.MapGet("/hello", () => new { Message = "Hello World" });
Return TypedResults
The following code returns a xref:Microsoft.AspNetCore.Http.TypedResults:
app.MapGet("/hello", () => TypedResults.Ok(new Message() { Text = "Hello World!" }));
Returning TypedResults
is preferred to returning xref:Microsoft.AspNetCore.Http.Results. For more information, see TypedResults vs Results.
IResult return values
app.MapGet("/hello", () => Results.Ok(new { Message = "Hello World" }));
The following example uses the built-in result types to customize the response:
JSON
app.MapGet("/hello", () => Results.Json(new { Message = "Hello World" }));
Custom Status Code
app.MapGet("/405", () => Results.StatusCode(405));
Text
app.MapGet("/text", () => Results.Text("This is some text"));
Stream
var proxyClient = new HttpClient();
app.MapGet("/pokemon", async () =>
{
var stream = await proxyClient.GetStreamAsync("http://consoto/pokedex.json");
// Proxy the response as JSON
return Results.Stream(stream, "application/json");
});
See xref:fundamentals/minimal-apis/responses#stream7 for more examples.
Redirect
app.MapGet("/old-path", () => Results.Redirect("/new-path"));
File
app.MapGet("/download", () => Results.File("myfile.text"));
Built-in results
[!INCLUDE results-helpers]
Customizing results
Applications can control responses by implementing a custom xref:Microsoft.AspNetCore.Http.IResult type. The following code is an example of an HTML result type:
We recommend adding an extension method to xref:Microsoft.AspNetCore.Http.IResultExtensions?displayProperty=fullName to make these custom results more discoverable.
Typed results
The xref:Microsoft.AspNetCore.Http.IResult interface can represent values returned from minimal APIs that don't utilize the implicit support for JSON serializing the returned object to the HTTP response. The static Results class is used to create varying IResult
objects that represent different types of responses. For example, setting the response status code or redirecting to another URL.
The types implementing IResult
are public, allowing for type assertions when testing. For example:
You can look at the return types of the corresponding methods on the static TypedResults class to find the correct public IResult
type to cast to.
See xref:fundamentals/minimal-apis/responses for more examples.
Filters
See xref:fundamentals/minimal-apis/min-api-filters
Authorization
Routes can be protected using authorization policies. These can be declared via the [Authorize]
attribute or by using the xref:Microsoft.AspNetCore.Builder.AuthorizationEndpointConventionBuilderExtensions.RequireAuthorization%2A method:
The preceding code can be written with xref:Microsoft.AspNetCore.Builder.AuthorizationEndpointConventionBuilderExtensions.RequireAuthorization%2A:
The following sample uses policy-based authorization:
Allow unauthenticated users to access an endpoint
The [AllowAnonymous]
allows unauthenticated users to access endpoints:
CORS
Routes can be CORS enabled using CORS policies. CORS can be declared via the [EnableCors]
attribute or by using the
xref:Microsoft.AspNetCore.Builder.CorsEndpointConventionBuilderExtensions.RequireCors%2A method. The following samples enable CORS:
For more information, see xref:security/cors?view=aspnetcore-6.0
See also
- xref:fundamentals/minimal-apis/openapi
- xref:fundamentals/minimal-apis/responses
- xref:fundamentals/minimal-apis/min-api-filters
- xref:fundamentals/minimal-apis/handle-errors
- xref:fundamentals/minimal-apis/security
- xref:fundamentals/minimal-apis/test-min-api
:::moniker-end