title | author | description | ms.author | content_well_notification | monikerRange | ms.date | uid | ai-usage |
---|---|---|---|---|---|---|---|---|
Minimal APIs quick reference |
rick-anderson |
Provides an overview of minimal APIs in ASP.NET Core |
riande |
AI-contribution |
>= aspnetcore-6.0 |
10/23/2023 |
fundamentals/minimal-apis |
ai-assisted |
:::moniker range=">= aspnetcore-8.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:
- WebApplication and WebApplicationBuilder
- Route Handlers
The following table lists some of the middleware frequently used with minimal APIs.
Middleware | Description | API |
---|---|---|
Authentication | Provides authentication support. | xref:Microsoft.AspNetCore.Builder.AuthAppBuilderExtensions.UseAuthentication%2A |
Authorization | Provides authorization support. | xref:Microsoft.AspNetCore.Builder.AuthorizationAppBuilderExtensions.UseAuthorization%2A |
CORS | Configures Cross-Origin Resource Sharing. | xref:Microsoft.AspNetCore.Builder.CorsMiddlewareExtensions.UseCors%2A |
Exception Handler | Globally handles exceptions thrown by the middleware pipeline. | xref:Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler%2A |
Forwarded Headers | Forwards proxied headers onto the current request. | xref:Microsoft.AspNetCore.Builder.ForwardedHeadersExtensions.UseForwardedHeaders%2A |
HTTPS Redirection | Redirects all HTTP requests to HTTPS. | xref:Microsoft.AspNetCore.Builder.HttpsPolicyBuilderExtensions.UseHttpsRedirection%2A |
HTTP Strict Transport Security (HSTS) | Security enhancement middleware that adds a special response header. | xref:Microsoft.AspNetCore.Builder.HstsBuilderExtensions.UseHsts%2A |
Request Logging | Provides support for logging HTTP requests and responses. | xref:Microsoft.AspNetCore.Builder.HttpLoggingBuilderExtensions.UseHttpLogging%2A |
Request Timeouts | Provides support for configuring request timeouts, global default and per endpoint. | UseRequestTimeouts |
W3C Request Logging | Provides support for logging HTTP requests and responses in the W3C format. | xref:Microsoft.AspNetCore.Builder.HttpLoggingBuilderExtensions.UseW3CLogging%2A |
Response Caching | Provides support for caching responses. | xref:Microsoft.AspNetCore.Builder.ResponseCachingExtensions.UseResponseCaching%2A |
Response Compression | Provides support for compressing responses. | xref:Microsoft.AspNetCore.Builder.ResponseCompressionBuilderExtensions.UseResponseCompression%2A |
Session | Provides support for managing user sessions. | xref:Microsoft.AspNetCore.Builder.SessionMiddlewareExtensions.UseSession%2A |
Static Files | Provides support for serving static files and directory browsing. | xref:Microsoft.AspNetCore.Builder.StaticFileExtensions.UseStaticFiles%2A, xref:Microsoft.AspNetCore.Builder.FileServerExtensions.UseFileServer%2A |
WebSockets | Enables the WebSockets protocol. | xref:Microsoft.AspNetCore.Builder.WebSocketMiddlewareExtensions.UseWebSockets%2A |
The following sections cover request handling: routing, parameter binding, and responses.
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".
[!INCLUDE route handling]
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
app.MapGet("/hello", () => "Hello World");
app.MapGet("/hello", () => new { Message = "Hello World" });
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.
app.MapGet("/hello", () => Results.Ok(new { Message = "Hello World" }));
The following example uses the built-in result types to customize the response:
app.MapGet("/hello", () => Results.Json(new { Message = "Hello World" }));
app.MapGet("/405", () => Results.StatusCode(405));
app.MapGet("/text", () => Results.Text("This is some text"));
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.
app.MapGet("/old-path", () => Results.Redirect("/new-path"));
app.MapGet("/download", () => Results.File("myfile.text"));
[!INCLUDE results-helpers]
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.
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.
See:
- xref:fundamentals/minimal-apis/min-api-filters
- A deep dive into endpoint filters
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:
The [AllowAnonymous]
allows unauthenticated users to access endpoints:
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
xref:Microsoft.Extensions.DependencyInjection.ServiceProviderOptions.ValidateScopes and xref:Microsoft.Extensions.DependencyInjection.ServiceProviderOptions.ValidateOnBuild are enabled by default in the Development environment but disabled in other environments.
When ValidateOnBuild
is true
, the DI container validates the service configuration at build time. If the service configuration is invalid, the build fails at app startup, rather than at runtime when the service is requested.
When ValidateScopes
is true
, the DI container validates that a scoped service isn't resolved from the root scope. Resolving a scoped service from the root scope can result in a memory leak because the service is retained in memory longer than the scope of the request.
ValidateScopes
and ValidateOnBuild
are false by default in non-Development modes for performance reasons.
The following code shows ValidateScopes
is enabled by default in development mode but disabled in release mode:
:::code language="csharp" source="~/../AspNetCore.Docs.Samples/fundamentals/minimal-apis/samples/ValidateOnBuildWeb/Program.cs" id="snippet_1" highlight="3,16-25":::
The following code shows ValidateOnBuild
is enabled by default in development mode but disabled in release mode:
:::code language="csharp" source="~/../AspNetCore.Docs.Samples/fundamentals/minimal-apis/samples/ValidateOnBuildWeb/Program.cs" id="snippet_vob" highlight="10":::
The following code disables ValidateScopes
and ValidateOnBuild
in Development
:
:::code language="csharp" source="~/../AspNetCore.Docs.Samples/fundamentals/minimal-apis/samples/ValidateOnBuildWeb/Program.cs" id="snippet_2":::
- xref:fundamentals/minimal-apis
- 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
- Short-circuit routing
- Identity API endpoints
- Keyed service dependency injection container support
- A look behind the scenes of minimal API endpoints
- Organizing ASP.NET Core Minimal APIs
- Fluent validation discussion on GitHub
:::moniker-end