Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix and Edit build time OpenAPI/ra/b #33361

Merged
merged 74 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
74 commits
Select commit Hold shift + click to select a range
df65929
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 14, 2024
42711fc
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 14, 2024
1649587
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 14, 2024
446a579
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 14, 2024
f6ea15c
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
d1f346d
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
acd7cb8
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
a9dcecf
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
b074ef6
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
450f254
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
ce6735f
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
82d8440
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
29b0b19
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
30cb83d
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
aa7a993
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
691ddd0
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
967964b
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
7207787
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
830bd95
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
bf29769
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
f8c51cb
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
03444b0
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
bc64f73
Fix and Edit build time OpenAPI/ra
Rick-Anderson Aug 15, 2024
8acbf92
Add SqlDB to skip
Rick-Anderson Aug 16, 2024
f54bd9d
Add SqlDB to skip
Rick-Anderson Aug 16, 2024
1b04232
Add SqlDB to skip
Rick-Anderson Aug 16, 2024
b21f9f5
Add SqlDB to skip
Rick-Anderson Aug 16, 2024
81fc99a
Add SqlDB to skip
Rick-Anderson Aug 16, 2024
1a1766d
Add SqlDB to skip
Rick-Anderson Aug 16, 2024
808fbb5
Add SqlDB to skip
Rick-Anderson Aug 16, 2024
21e62a2
Add SqlDB to skip
Rick-Anderson Aug 16, 2024
ee50266
Add SqlDB to skip
Rick-Anderson Aug 16, 2024
9f95b57
Add SqlDB to skip
Rick-Anderson Aug 16, 2024
b5d98ea
Apply suggestions from code review
Rick-Anderson Aug 16, 2024
419d0f6
Add SqlDB to skip
Rick-Anderson Aug 16, 2024
feebbda
react to feedback
Rick-Anderson Aug 16, 2024
b6469ca
react to feedback
Rick-Anderson Aug 17, 2024
38ecacb
react to feedback
Rick-Anderson Aug 17, 2024
739dcb5
react to feedback
Rick-Anderson Aug 19, 2024
52d682a
react to feedback
Rick-Anderson Aug 19, 2024
d298ace
react to feedback
Rick-Anderson Aug 19, 2024
854f69a
react to feedback
Rick-Anderson Aug 19, 2024
67c2271
react to feedback
Rick-Anderson Aug 19, 2024
0601997
fix script
Rick-Anderson Aug 19, 2024
df90ae3
fix script
Rick-Anderson Aug 20, 2024
8b6a7d5
fix script
Rick-Anderson Aug 20, 2024
2befcb7
fix script
Rick-Anderson Aug 20, 2024
025d0dc
fix script
Rick-Anderson Aug 20, 2024
101ac83
fix script
Rick-Anderson Aug 20, 2024
94bf18e
fix script
Rick-Anderson Aug 20, 2024
4f0bc88
fix script
Rick-Anderson Aug 20, 2024
a52ff1e
fix script
Rick-Anderson Aug 20, 2024
62e3480
fix script
Rick-Anderson Aug 20, 2024
078a6a6
fix script
Rick-Anderson Aug 20, 2024
e575f9a
fix script
Rick-Anderson Aug 21, 2024
3365563
fix script
Rick-Anderson Aug 22, 2024
49b9864
fix script
Rick-Anderson Aug 22, 2024
0cfbe8b
fix script
Rick-Anderson Aug 22, 2024
dd69fe2
fix script
Rick-Anderson Aug 22, 2024
7b320ba
fix script
Rick-Anderson Aug 22, 2024
6200d10
fix script
Rick-Anderson Aug 22, 2024
3dc0d25
fix script
Rick-Anderson Aug 22, 2024
ff894ff
fix script
Rick-Anderson Aug 22, 2024
5b87bda
fix script
Rick-Anderson Aug 22, 2024
3e4eca5
fix script
Rick-Anderson Aug 22, 2024
ecc1640
fix script
Rick-Anderson Aug 22, 2024
e607a14
react to feedback V2
Rick-Anderson Aug 22, 2024
c6cee5f
react to feedback V2
Rick-Anderson Aug 23, 2024
b798c9a
react to feedback V2
Rick-Anderson Aug 23, 2024
8a0df43
react to feedback V2
Rick-Anderson Sep 3, 2024
6276727
react to feedback V2
Rick-Anderson Sep 3, 2024
7af037a
Apply suggestions from code review
Rick-Anderson Oct 4, 2024
6711ec1
Fix toc merge conflict
Rick-Anderson Oct 4, 2024
82ddc0e
add comment it's V9
Rick-Anderson Oct 4, 2024
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
24 changes: 13 additions & 11 deletions aspnetcore/fundamentals/openapi/aspnetcore-openapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ ms.custom: mvc
ms.date: 5/22/2024
uid: fundamentals/openapi/aspnetcore-openapi
---
<!-- backup writer.sms.author: tdykstra and rick-anderson -->

# Work with OpenAPI documents

:::moniker range=">= aspnetcore-9.0"
Expand Down Expand Up @@ -67,7 +69,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 @@ -400,13 +402,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, it's possible to limit access to the OpenAPI document. For example, 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 @@ -434,13 +436,13 @@ Transformers can be registered onto the document via the `AddDocumentTransformer
* Register a document transformer using a DI-activated `IOpenApiDocumentTransformer`.
* Register an operation transformer using a delegate.

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

### 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 @@ -452,18 +454,18 @@ Document transformers have access to a context object that includes:

Document transformers also can 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 `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 @@ -480,7 +482,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)]

## Using the generated OpenAPI document

Expand All @@ -494,13 +496,13 @@ 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. 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)]

### Using Scalar for interactive API documentation

[Scalar](https://scalar.com/) is an open-source interactive document UI for OpenAPI. Scalar can integrate with the OpenAPI endpoint provided by ASP.NET Core. To configure Scalar, install the `Scalar.AspNetCore` package.

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

### Lint generated OpenAPI documents with Spectral

Expand Down
107 changes: 70 additions & 37 deletions aspnetcore/fundamentals/openapi/buildtime-openapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,19 @@ ms.custom: mvc
ms.date: 8/13/2024
captainsafia marked this conversation as resolved.
Show resolved Hide resolved
uid: fundamentals/openapi/buildtime-openapi
---
<!-- backup writer.sms.author: tdykstra and rick-anderson -->

# Generate OpenAPI documents at build-time

In a typical web applications, OpenAPI documents are generated at run-time and served via an HTTP request to the application server.
In a typical web apps, OpenAPI documents are generated at run-time and served via an HTTP request to the app server.
Rick-Anderson marked this conversation as resolved.
Show resolved Hide resolved

In some scenarios, it is helpful to generate the OpenAPI document during the application's build step. These scenarios including:
Generating OpenAPI documentation during the app's build step can be useful for documentation that is:

- 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
- Committed into source control
- Used for spec-based integration testing
- Served statically from the web server

To add support for generating OpenAPI documents at build time, install the `Microsoft.Extensions.ApiDescription.Server` package:
To add support for generating OpenAPI documents at build time, install the [`Microsoft.Extensions.ApiDescription.Server`](https://www.nuget.org/packages/Microsoft.Extensions.ApiDescription.Server) NuGet package:

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

Expand All @@ -36,57 +37,85 @@ 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.
The `Microsoft.Extensions.ApiDescription.Server` package automatically generates the Open API document(s) associated with the app during build and places them in the app's `obj` directory:
Copy link
Member

Choose a reason for hiding this comment

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

Is obj right? I would have thought it would be in the output directory (or should be) so be within bin.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@captainsafia drafted this as the output directory and maybe that's where it will end up. In my testing, it's in the obj directory.

Copy link
Contributor Author

@Rick-Anderson Rick-Anderson Aug 17, 2024

Choose a reason for hiding this comment

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

run /TestScripts/combined.ps1
what version of RC1 do you have?
I have 9.0.100-rc.1.24415.1

Copy link
Contributor

Choose a reason for hiding this comment

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

My testing also shows that the default location is the obj directory, but you can change that (and I always do) with this setting in the project file:

  <PropertyGroup>
    <OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)</OpenApiDocumentsDirectory>
  </PropertyGroup>


Consider a template created API app named `MyTestApi`:

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

The Output tab in Visual Studio includes information similar to the following:

```text
1>Generating document named 'v1'.
1>Writing document named 'v1' to 'MyProjectPath\obj\MyTestApi.json'.
```

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

The following commands build the app and display the generated OpenAPI document:

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

## Customizing build-time document generation
---

### Modifying the output directory of the generated Open API file
The generated `obj/{MyProjectName}.json` file contains the [OpenAPI version, title, endpoints, and more](https://learn.openapis.org/specification/structure.html). The first few lines of obj/MyTestApi.json 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.
:::code language="json" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.json" id="snippet_1" highlight="4-5":::

```xml
<PropertyGroup>
<OpenApiDocumentsDirectory>./</OpenApiDocumentsDirectory>
Rick-Anderson marked this conversation as resolved.
Show resolved Hide resolved
</PropertyGroup>
```
## Customize build-time document generation

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.
### Modify the output directory of the generated Open API file

### Modifying the output file name
By default, the generated OpenAPI document is generated in the app's output directory. To modify the location of the generated file, set the target path in the `OpenApiDocumentsDirectory` property in the project file:

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.
:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.html" id="snippet_1" highlight="2":::

```xml
<PropertyGroup>
<OpenApiGenerateDocumentsOptions>--file-name my-open-api</OpenApiGenerateDocumentsOptions>
</PropertyGroup>
```
The value of `OpenApiDocumentsDirectory` is resolved relative to the project file. Using the `.` value in the preceding markup generates the OpenAPI document in the same directory as the project file. To generate the OpenAPI document in a different directory, provide the path relative to the project file. In the following example, the OpenAPI document is generated in the `MyOpenApiDocs` directory, which is a sibling directory of the project directory:

### Selecting the OpenAPI document to generate
:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.html" id="snippet2" highlight="2":::

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.
### Modify the output file name

```xml
<PropertyGroup>
<OpenApiGenerateDocumentsOptions>--document-name v2</OpenApiGenerateDocumentsOptions>
</PropertyGroup>
```
By default, the generated OpenAPI document has the same name as the app's project file. To modify the name of the generated file, set the `--file-name` argument in the `OpenApiGenerateDocumentsOptions` property:
Copy link
Member

Choose a reason for hiding this comment

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

This isn't what I've seen in my testing. I get something like ProjectName_DocumentName.json (e.g. API_v1.json).

Copy link
Contributor Author

@Rick-Anderson Rick-Anderson Aug 17, 2024

Choose a reason for hiding this comment

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

This isn't what I've seen in my testing. I get something like ProjectName_DocumentName.json (e.g. API_v1.json).

My build is 9.0.100-rc.1.24415.1
run /TestScripts/combined.ps1


:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.html" id="snippet_file_name" highlight="2":::

The preceding markup generates the `obj/my-open-api.json` file.

### Select the OpenAPI document to generate

Some apps may be configured to generate multiple OpenAPI documents, for example:

## Customizing run-time behavior during build-time document generation
* For different versions of an API.
* To distinguish between public and internal APIs.

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:
By default, the build-time document generator creates files for all documents that are configured in an app. To generate for a single document only, set the `--document-name` argument in the `OpenApiGenerateDocumentsOptions` property:

- Not reading from certain configuration strings
- Not registering database-related services
:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.html" id="snippet_doc_name":::

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:
<!--
What's the equivalent of
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Public API v1");
c.SwaggerEndpoint("/swagger/v2/swagger.json", "Internal API v2");
});
-->

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

The OpenAPI document generation at build-time works by starting the app’s entrypoint with a temporary background server. This is a requirement to produce accurate OpenAPI documents because all information in the OpenAPI document can't be statically analyzed. Because the app's entrypoint is invoked, any logic in the apps' startup is invoked. The app's entrypoint includes code that injects services into the DI container or reads from configuration. In some scenarios, it's necessary to restrict the code paths that run when the app'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 code paths from being invoked by the build-time generation pipeline, they can be conditioned behind a check of the entry assembly:

```csharp
using System.Reflection;
Expand All @@ -95,6 +124,10 @@ var builder = WebApplication.CreateBuilder();

if (Assembly.GetEntryAssembly()?.GetName().Name != "GetDocument.Insider")
{
builders.Services.AddDefaults();
builder.Services.AddDefaults();
}
```

## OpenAPI document cleanup

Then generated OpenAPI documents are not cleaned up by `dotnet clean` or **Build > Clean Solution** in Visual Studio. To clean up the generated OpenAPI documents, delete the `obj` directory or the directory where the OpenAPI documents are generated.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="[9.0.0-rc.1.24414.4, 10.0.0)" />

<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="[9.0.0-rc.1.24414.4, 10.0.0)">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@MyTestApi_HostAddress = http://localhost:5276

GET {{MyTestApi_HostAddress}}/weatherforecast/
Accept: application/json

###
46 changes: 46 additions & 0 deletions aspnetcore/fundamentals/openapi/samples/9.x/BuildTime/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System.Reflection;

var builder = WebApplication.CreateBuilder();

if (Assembly.GetEntryAssembly()?.GetName().Name != "GetDocument.Insider")
{
// builder.Services.AddDefaults();
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

builder.Services.AddDefaults(); generates the error:
'IServiceCollection' does not contain a definition for 'AddDefaults'

Copy link
Member

Choose a reason for hiding this comment

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

This is my bad...I had trouble figuring out what would be a good illustration of a setup here.

Maybe we can do something that configures an EF Core DB context?

services.AddDbContext<MyContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

We'd have to add a definition for MyContext and the package references for EF

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@captainsafia @martincostello

This is my bad...I had trouble figuring out what would be a good illustration of a setup here.

Maybe we can do something that configures an EF Core DB context?

services.AddDbContext<MyContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

We'd have to add a definition for MyContext and the package references for EF

I have:


builder.Services.AddAuthorization();

// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}

app.UseHttpsRedirection();

app.UseAuthorization();

var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
Copy link
Member

Choose a reason for hiding this comment

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

Wonky indentation.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Wonky indentation.

Template generated, I didn't change it. This code isn't shown in the article. I started with the API templates.

};

app.MapGet("/weatherforecast", (HttpContext httpContext) =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = summaries[Random.Shared.Next(summaries.Length)]
})
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast");

app.Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
public class WeatherForecast
{
public DateOnly Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

public string? Summary { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<!--
This file is needed to contain snippets and provides a convient
location to copy/paste the <PropertyGroup> into the .csproj file.
The dash dash sequence is an illegal string in an XML comment and
results in the error: An XML comment cannot contain --.

That's why this is stored as an HTML file.
-->
<!-- <snippet_file_name> -->
<PropertyGroup>
<OpenApiGenerateDocumentsOptions>--file-name my-open-api</OpenApiGenerateDocumentsOptions>
</PropertyGroup>
<!-- </snippet_file_name> -->
<!--<snippet_1>-->
<PropertyGroup>
<OpenApiDocumentsDirectory>.</OpenApiDocumentsDirectory>
</PropertyGroup>
<!--</snippet_1>-->
<!--<snippet2>-->
<PropertyGroup>
<OpenApiDocumentsDirectory>../MyOpenApiDocs</OpenApiDocumentsDirectory>
</PropertyGroup>
<!--</snippet2>-->
<!--<snippet_doc_name>-->
<PropertyGroup>
<OpenApiGenerateDocumentsOptions>--document-name v2</OpenApiGenerateDocumentsOptions>
</PropertyGroup>
<!--</snippet_doc_name>-->
Loading
Loading