Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions aspnetcore/fundamentals/minimal-apis/responses.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Minimal endpoints support the following types of return values:

Consider the following route handler, which returns a `Hello world` text.

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_01":::
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/Snippets/Program.cs" id="snippet_01":::

The `200` status code is returned with `text/plain` Content-Type header and the following content.

Expand All @@ -44,7 +44,7 @@ Hello World

Consider the following route handler, which returns an anonymous type containing a `Message` string property.

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_02":::
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/Snippets/Program.cs" id="snippet_02":::

The `200` status code is returned with `application/json` Content-Type header and the following content.

Expand Down Expand Up @@ -114,11 +114,11 @@ This has the added benefit of providing compile-time checking that a route handl

Consider the following endpoint, for which a `400 BadRequest` status code is returned when the `orderId` is greater than `999`. Otherwise, it produces a `200 OK` with the expected content.

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_03":::
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/Snippets/Program.cs" id="snippet_03":::

In order to document this endpoint correctly the extension method `Produces` is called. However, since the `TypedResults` helper automatically includes the metadata for the endpoint, you can return the `Results<T1, Tn>` union type instead, as shown in the following code.

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_04":::
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/Snippets/Program.cs" id="snippet_04":::

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

Expand All @@ -130,25 +130,25 @@ The following sections demonstrate the usage of the common result helpers.

#### JSON

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_05":::
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/Snippets/Program.cs" id="snippet_05":::

<xref:Microsoft.AspNetCore.Http.HttpResponseJsonExtensions.WriteAsJsonAsync%2A> is an alternative way to return JSON:

:::code language="csharp" source="~/fundamentals/minimal-apis/7.0-samples/WebMinJson/Program.cs" id="snippet_writeasjsonasync":::

#### Custom Status Code

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_06":::
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/Snippets/Program.cs" id="snippet_06":::

#### Internal Server Error

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_07":::
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/Snippets/Program.cs" id="snippet_07":::

The preceding example returns a 500 status code.

#### Text

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_08":::
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/Snippets/Program.cs" id="snippet_08":::

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

Expand All @@ -170,11 +170,11 @@ The following example streams a video from an Azure Blob:

#### Redirect

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_09":::
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/Snippets/Program.cs" id="snippet_09":::

#### File

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_10":::
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/Snippets/Program.cs" id="snippet_10":::

<a name="httpresultinterfaces7"></a>

Expand Down Expand Up @@ -215,7 +215,7 @@ The `ProducesHtmlMetadata` is an implementation of <xref:Microsoft.AspNetCore.Ht

An alternative approach is using the <xref:Microsoft.AspNetCore.Mvc.ProducesAttribute?displayProperty=fullName> to describe the produced response. The following code changes the `PopulateMetadata` method to use `ProducesAttribute`.

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_11":::
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/Snippets/Program.cs" id="snippet_11":::

## Configure JSON serialization options

Expand Down
20 changes: 10 additions & 10 deletions aspnetcore/fundamentals/openapi/aspnetcore-openapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ The following code:
* Adds OpenAPI services.
* Enables the endpoint for viewing the OpenAPI document in JSON format.

[!code-csharp[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs?name=snippet_first&highlight=3,7)]
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_first&highlight=3,7)]

Launch the app and navigate to `https://localhost:<port>/openapi/v1.json` to view the generated OpenAPI document.

Expand Down Expand Up @@ -649,13 +649,13 @@ Because the OpenAPI document is served via a route handler endpoint, any customi

The OpenAPI endpoint doesn't enable any authorization checks by default. However, authorization checks can be applied to the OpenAPI document. In the following code, access to the OpenAPI document is limited to those with the `tester` role:

[!code-csharp[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs?name=snippet_mapopenapiwithauth)]
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_mapopenapiwithauth)]

#### Cache generated OpenAPI document

The OpenAPI document is regenerated every time a request to the OpenAPI endpoint is sent. Regeneration enables transformers to incorporate dynamic application state into their operation. For example, regenerating a request with details of the HTTP context. When applicable, the OpenAPI document can be cached to avoid executing the document generation pipeline on each HTTP request.

[!code-csharp[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs?name=snippet_mapopenapiwithcaching)]
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_mapopenapiwithcaching)]

<a name="transformers"></a>

Expand Down Expand Up @@ -689,13 +689,13 @@ Transformers can be registered onto the document by calling the <xref:Microsoft.
* Register a schema transformer using an instance of <xref:Microsoft.AspNetCore.OpenApi.IOpenApiSchemaTransformer>.
* Register a schema transformer using a DI-activated <xref:Microsoft.AspNetCore.OpenApi.IOpenApiSchemaTransformer>.

[!code-csharp[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs?name=snippet_transUse&highlight=8-19)]
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_transUse&highlight=8-19)]

### Execution order for transformers

Transformers execute in first-in first-out order based on registration. In the following snippet, the document transformer has access to the modifications made by the operation transformer:

[!code-csharp[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs?name=snippet_transInOut&highlight=3-9)]
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_transInOut&highlight=3-9)]

### Use document transformers

Expand All @@ -707,18 +707,18 @@ Document transformers have access to a context object that includes:

Document transformers can also mutate the OpenAPI document that is generated. The following example demonstrates a document transformer that adds some information about the API to the OpenAPI document.

[!code-csharp[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs?name=snippet_documenttransformer1)]
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_documenttransformer1)]

Service-activated document transformers can utilize instances from DI to modify the app. The following sample demonstrates a document transformer that uses the <xref:Microsoft.AspNetCore.Authentication.IAuthenticationSchemeProvider> service from the authentication layer. It checks if any JWT bearer-related schemes are registered in the app and adds them to the OpenAPI document's top level:

[!code-csharp[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs?name=snippet_documenttransformer2)]
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_documenttransformer2)]

Document transformers are unique to the document instance they're associated with. In the following example, a transformer:

* Registers authentication-related requirements to the `internal` document.
* Leaves the `public` document unmodified.

[!code-csharp[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs?name=snippet_multidoc_operationtransformer1)]
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_multidoc_operationtransformer1)]

### Use operation transformers

Expand All @@ -735,7 +735,7 @@ Operation transformers have access to a context object which contains:

For example, the following operation transformer adds `500` as a response status code supported by all operations in the document.

[!code-csharp[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs?name=snippet_operationtransformer1)]
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_operationtransformer1)]

### Use schema transformers

Expand All @@ -752,7 +752,7 @@ Schema transformers have access to a context object which contains:

For example, the following schema transformer sets the `format` of decimal types to `decimal` instead of `double`:

[!code-csharp[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs?name=snippet_schematransformer1)]
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_schematransformer1)]

## Additional resources

Expand Down
100 changes: 100 additions & 0 deletions aspnetcore/fundamentals/openapi/buildtime-openapi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
---
title: Generate OpenAPI documents at build time
author: captainsafia
description: Learn how to generate OpenAPI documents in your application's build step
ms.author: safia
monikerRange: '>= aspnetcore-6.0'
ms.custom: mvc
ms.date: 8/13/2024
uid: fundamentals/openapi/buildtime-openapi
---

# Generate OpenAPI documents at build-time
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Rick-Anderson @tdykstra This definitely needs some massaging for prose and formatting but the material covered is true to what I think we should cover. Feel free to modify this branch as you see fit.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Rick-Anderson @tdykstra This definitely needs some massaging for prose and formatting but the material covered is true to what I think we should cover. Feel free to modify this branch as you see fit.

Can I merge #33361 into this branch? You've reviewed #33361 and @mikekistler has approved my changes. My PR fixes the toc.yml merge conflict. I think I can easily fix the other merge conflicts.


In a typical web applications, OpenAPI documents are generated at run-time and served via an HTTP request to the application server.

In some scenarios, it is helpful to generate the OpenAPI document during the application's build step. These scenarios including:

- Generating OpenAPI documentation that is committed into source control
- Generating OpenAPI documentation that is used for spec-based integration testing
- Generating OpenAPI documentation that is served statically from the web server

To add support for generating OpenAPI documents at build time, install the `Microsoft.Extensions.ApiDescription.Server` package:

### [Visual Studio](#tab/visual-studio)

Run the following command from the **Package Manager Console**:

```powershell
Install-Package Microsoft.Extensions.ApiDescription.Server -IncludePrerelease
```

### [.NET CLI](#tab/net-cli)

Run the following command in the directory that contains the project file:

```dotnetcli
dotnet add package Microsoft.Extensions.ApiDescription.Server --prerelease
```
---

Upon installation, this package will automatically generate the Open API document(s) associated with the application during build and populate them into the application's output directory.

```cli
$ dotnet build
$ cat bin/Debub/net9.0/{ProjectName}.json
```

## Customizing build-time document generation

### Modifying the output directory of the generated Open API file

By default, the generated OpenAPI document will be emitted to the application's output directory. To modify the location of the emitted file, set the target path in the `OpenApiDocumentsDirectory` property.

```xml
<PropertyGroup>
<OpenApiDocumentsDirectory>./</OpenApiDocumentsDirectory>
</PropertyGroup>
```

The value of `OpenApiDocumentsDirectory` is resolved relative to the project file. Using the `./` value above will emit the OpenAPI document in the same directory as the project file.

### Modifying the output file name

By default, the generated OpenAPI document will have the same name as the application's project file. To modify the name of the emitted file, set the `--file-name` argument in the `OpenApiGenerateDocumentsOptions` property.

```xml
<PropertyGroup>
<OpenApiGenerateDocumentsOptions>--file-name my-open-api</OpenApiGenerateDocumentsOptions>
</PropertyGroup>
```

### Selecting the OpenAPI document to generate

Some applications may be configured to emit multiple OpenAPI documents, for various versions of an API or to distinguish between public and internal APIs. By default, the build-time document generator will emit files for all documents that are configured in an application. To only emit for a single document name, set the `--document-name` argument in the `OpenApiGenerateDocumentsOptions` property.

```xml
<PropertyGroup>
<OpenApiGenerateDocumentsOptions>--document-name v2</OpenApiGenerateDocumentsOptions>
</PropertyGroup>
```

## Customizing run-time behavior during build-time document generation

Under the hood, build-time OpenAPI document generation functions by launching the application's entrypoint with an inert server implementation. This is a requirement to produce accurate OpenAPI documents since all information in the OpenAPI document cannot be statically analyzed. Because the application's entrypoint is invoked, any logic in the applications' startup will be invoked. This includes code that injects services into the DI container or reads from configuration. In some scenarios, it's necessary to restrict the codepaths that will run when the application's entry point is being invoked from build-time document generation. These scenarios include:

- Not reading from certain configuration strings
- Not registering database-related services

In order to restrict these codepaths from being invoked by the build-time generation pipeline, they can be conditioned behind a check of the entry assembly like so:

```csharp
using System.Reflection;

var builder = WebApplication.CreateBuilder();

if (Assembly.GetEntryAssembly()?.GetName().Name != "GetDocument.Insider")
{
builders.Services.AddDefaults();
}
```
6 changes: 3 additions & 3 deletions aspnetcore/fundamentals/openapi/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ ASP.NET Core apps provide built-in support for generating information about endp

The following code is generated by the ASP.NET Core minimal web API template and uses OpenAPI:

[!code-csharp[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs?name=snippet_default&highlight=5,9-12)]
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_default&highlight=5,9-12)]

In the preceding highlighted code:

Expand All @@ -45,7 +45,7 @@ The [`Microsoft.AspNetCore.OpenApi`](https://www.nuget.org/packages/Microsoft.As

To use the `Microsoft.AspNetCore.OpenApi` package, add it as a PackageReference to a project file:

[!code-xml[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/projectFile.xml?highlight=15)]
[!code-xml[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/projectFile.xml?highlight=15)]

To learn more about the `Microsoft.AspNetCore.OpenApi` package, see <xref:fundamentals/openapi/aspnetcore-openapi>.

Expand All @@ -58,7 +58,7 @@ Document generation at build time is enabled by setting the `OpenApiGenerateDocu
By default, the generated OpenAPI document is saved to the `obj` directory, but you can customize
the output directory by setting the `OpenApiDocumentsDirectory` property.

[!code-xml[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/projectFile.xml?highlight=9-12,16-19)]
[!code-xml[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/projectFile.xml?highlight=9-12,16-19)]

## ASP.NET Core OpenAPI source code on GitHub

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<OpenApiDocumentsDirectory>./</OpenApiDocumentsDirectory>
<OpenApiGenerateDocumentsOptions>--file-name my-open-api</OpenApiGenerateDocumentsOptions>
</PropertyGroup>

<PropertyGroup>
Expand All @@ -19,7 +21,7 @@
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Scalar.AspNetCore" Version="1.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUi" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUi" Version="6.7.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"sdk": {
"version": "9.0.100-rc.1.24414.13"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"openapi": "3.0.1",
"info": {
"title": "GetDocument.Insider | v1",
"version": "1.0.0"
},
"paths": {
"/": {
"get": {
"tags": [
"GetDocument.Insider"
],
"responses": {
"200": {
"description": "OK",
"content": {
"text/plain": {
"schema": {
"type": "string"
}
}
}
}
}
}
}
},
"components": { },
"tags": [
{
"name": "GetDocument.Insider"
}
]
}
4 changes: 2 additions & 2 deletions aspnetcore/fundamentals/openapi/using-openapi-documents.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ The `Swashbuckle.AspNetCore.SwaggerUi` package provides a bundle of Swagger UI's
* Enable the swagger-ui middleware with a reference to the [OpenAPI route registered earlier](xref:fundamentals/openapi/aspnetcore-openapi#customize-the-openapi-endpoint-route).
* To limit information disclosure and security vulnerability, ***only enable Swagger UI in development environments.***

[!code-csharp[](~/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs?name=snippet_swaggerui)]
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_swaggerui)]

## Use Scalar for interactive API documentation

Expand Down Expand Up @@ -76,4 +76,4 @@ The output shows any issues with the OpenAPI document. For example:
```
:::moniker-end

[!INCLUDE[](~/fundamentals/openapi/includes/using-openapi-documents-6-8.md)]
[!INCLUDE[](~/fundamentals/openapi/includes/using-openapi-documents-6-8.md)]
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ OpenAPI transformers support modifying the OpenAPI document, operations within t
Previously, the following APIs were available for registering transformers:

```csharp
OpenApiOptions UseTransformer(Func<OpenApiDocument, OpenApiDocumentTransformerContext, CancellationToken, Task> transformer)
OpenApiOptions UseTransformer(IOpenApiDocumentTransformer transformer)
OpenApiOptions UseTransformer<IOpenApiDocumentTransformer>()
OpenApiOptions AddDocumentTransformer(Func<OpenApiDocument, OpenApiDocumentTransformerContext, CancellationToken, Task> transformer)
OpenApiOptions AddDocumentTransformer(IOpenApiDocumentTransformer transformer)
OpenApiOptions AddDocumentTransformer<IOpenApiDocumentTransformer>()
OpenApiOptions UseSchemaTransformer(Func<OpenApiSchema, OpenApiSchemaTransformerContext, CancellationToken, Task>)
OpenApiOptions UseOperationTransformer(Func<OpenApiOperation, OpenApiOperationTransformerContext, CancellationToken, Task>)
OpenApiOptions AddOperationTransformer(Func<OpenApiOperation, OpenApiOperationTransformerContext, CancellationToken, Task>)
```

The new API set is as follows:
Expand Down
2 changes: 2 additions & 0 deletions aspnetcore/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -878,6 +878,8 @@ items:
uid: fundamentals/openapi/aspnetcore-openapi
- name: Use OpenAPI documents
uid: fundamentals/openapi/using-openapi-documents
- name: Generate OpenAPI documents at build-time
uid: fundamentals/openapi/buildtime-openapi
- name: OpenAPI tools
uid: fundamentals/openapi/openapi-tools
- name: Swagger / NSwag
Expand Down
Loading