Back to Aspnetcore

Minimal Apis7

aspnetcore/fundamentals/minimal-apis/includes/minimal-apis7.md

latest10.8 KB
Original Source

:::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.

MiddlewareDescriptionAPI
AuthenticationProvides authentication support.xref:Microsoft.AspNetCore.Builder.AuthAppBuilderExtensions.UseAuthentication%2A
AuthorizationProvides authorization support.xref:Microsoft.AspNetCore.Builder.AuthorizationAppBuilderExtensions.UseAuthorization%2A
CORSConfigures Cross-Origin Resource Sharing.xref:Microsoft.AspNetCore.Builder.CorsMiddlewareExtensions.UseCors%2A
Exception HandlerGlobally handles exceptions thrown by the middleware pipeline.xref:Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler%2A
Forwarded HeadersForwards proxied headers onto the current request.xref:Microsoft.AspNetCore.Builder.ForwardedHeadersExtensions.UseForwardedHeaders%2A
HTTPS RedirectionRedirects 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 LoggingProvides support for logging HTTP requests and responses.xref:Microsoft.AspNetCore.Builder.HttpLoggingBuilderExtensions.UseHttpLogging%2A
Request TimeoutsProvides support for configuring request timeouts, global default and per endpoint.UseRequestTimeouts
W3C Request LoggingProvides support for logging HTTP requests and responses in the W3C format.xref:Microsoft.AspNetCore.Builder.HttpLoggingBuilderExtensions.UseW3CLogging%2A
Response CachingProvides support for caching responses.xref:Microsoft.AspNetCore.Builder.ResponseCachingExtensions.UseResponseCaching%2A
Response CompressionProvides support for compressing responses.xref:Microsoft.AspNetCore.Builder.ResponseCompressionBuilderExtensions.UseResponseCompression%2A
SessionProvides support for managing user sessions.xref:Microsoft.AspNetCore.Builder.SessionMiddlewareExtensions.UseSession%2A
Static FilesProvides support for serving static files and directory browsing.xref:Microsoft.AspNetCore.Builder.StaticFileExtensions.UseStaticFiles%2A, xref:Microsoft.AspNetCore.Builder.FileServerExtensions.UseFileServer%2A
WebSocketsEnables 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 ]

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 valueBehaviorContent-Type
IResultThe framework calls IResult.ExecuteAsyncDecided by the IResult implementation
stringThe framework writes the string directly to the responsetext/plain
T (Any other type)The framework JSON-serializes the responseapplication/json

For a more in-depth guide to route handler return values see xref:fundamentals/minimal-apis/responses

Example return values

string return values

csharp
app.MapGet("/hello", () => "Hello World");

JSON return values

csharp
app.MapGet("/hello", () => new { Message = "Hello World" });

Return TypedResults

The following code returns a xref:Microsoft.AspNetCore.Http.TypedResults:

csharp
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

csharp
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

csharp
app.MapGet("/hello", () => Results.Json(new { Message = "Hello World" }));

Custom Status Code

csharp
app.MapGet("/405", () => Results.StatusCode(405));

Text

csharp
app.MapGet("/text", () => Results.Text("This is some text"));

<a name="stream7"></a>

Stream

csharp
var proxyClient = new HttpClient();
app.MapGet("/pokemon", async () => 
{
    var stream = await proxyClient.GetStreamAsync("http://contoso/pokedex.json");
    // Proxy the response as JSON
    return Results.Stream(stream, "application/json");
});

See xref:fundamentals/minimal-apis/responses#stream7 for more examples.

Redirect

csharp
app.MapGet("/old-path", () => Results.Redirect("/new-path"));

File

csharp
app.MapGet("/download", () => Results.File("myfile.text"));

<a name="binr7"></a>

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

<a name="openapi7"></a>

<!-- # Differences between Minimal APIs and APIs with controllers Moved to uid: tutorials/min-web-api -->

See also

:::moniker-end