AspNetCore.Docs/aspnetcore/fundamentals/minimal-apis.md

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.

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.

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:

[!code-csharp]

The xref:System.Delegate arguments passed to these methods are called "route handlers".

Route Handlers

[!INCLUDE route handling]

Parameter binding

[!INCLUDE ] [!INCLUDE ]

Responses

Route handlers support the following types of return values:

  1. IResult based - This includes Task<IResult> and ValueTask<IResult>
  2. string - This includes Task<string> and ValueTask<string>
  3. T (Any other type) - This includes Task<T> and ValueTask<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:

[!code-csharp]

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:

[!code-csharp]

We recommend adding an extension method to xref:Microsoft.AspNetCore.Http.IResultExtensions?displayProperty=fullName to make these custom results more discoverable.

[!code-csharp]

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:

[!code-csharp]

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:

[!code-csharp]

The preceding code can be written with xref:Microsoft.AspNetCore.Builder.AuthorizationEndpointConventionBuilderExtensions.RequireAuthorization%2A:

[!code-csharp]

The following sample uses policy-based authorization:

[!code-csharp]

Allow unauthenticated users to access an endpoint

The [AllowAnonymous] allows unauthenticated users to access endpoints:

[!code-csharp]

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:

[!code-csharp]

[!code-csharp]

For more information, see xref:security/cors?view=aspnetcore-6.0

See also

:::moniker-end

[!INCLUDE]