# apigenie-generator server aspnet

Source: https://apigenie.pl/docs/reference/generator/server-aspnet
Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md).
Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md).

[Tier 1](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification)

Generate an ASP.NET Core server in C#, built on Minimal APIs.

From an AsyncAPI document, the command generates an ASP.NET Core Kafka application instead; see
[`apigenie-generator server aspnet` (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi).

## Usage

```sh
apigenie-generator server aspnet [...OPTIONS] INPUT_FILE
```

## Description

The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see
[Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing other
files with [`apigenie bundle`](/docs/reference/cli/bundle).

The generated project targets .NET 8 (or 9 and 10, see `target_framework`) and uses only the
shared framework, without NuGet packages:

```
PetStore.csproj
Program.cs                  the host, written only when missing
README.md
ApiRegistration.cs          MapPetStoreApi(): maps the endpoints of all operations
Apis/IPetsApi.cs            one interface per group of operations
Apis/PetsApi.cs             its implementation, written only when missing
Endpoints/PetsEndpoints.cs  routes, parameter binding, validation and metadata
Models/Pet.cs               records and enums of the schemas
Senders/*.cs                typed HTTP clients sending the webhooks and callbacks
Infrastructure/*.cs         helpers used by the generated code
```

Operations are grouped by their first tag (or by the first segment of their paths). Each group
gets an interface whose methods return the responses of the operation as a union of typed
results, so the compiler accepts only declared responses:

```csharp
public interface IPetsApi
{
    /// <summary>Find a pet</summary>
    /// <remarks>GET /pets/{petId}</remarks>
    Task<Results<Ok<Pet>, NotFound, GoneResult<Error>>> GetPet(long petId, CancellationToken cancellationToken);
}
```

Implementations return `TypedResults.Ok(pet)`, `TypedResults.NotFound()` and the like. Statuses
without a `TypedResults` method (403, 410, 429, 500, ...) have result types of their own, created
with `ApiResults.Gone(error)`. All results describe their responses in the endpoint metadata, so
OpenAPI documents produced by ASP.NET Core match the input.

Since 0.12.0, a response with several media types has a result for each kind, and the
implementation picks one, e.g. by the `Accept` header of the request. Files (PDF, PNG, ...) are
`FileStreamHttpResult`, text is `ContentHttpResult`. `text/event-stream` is
`ServerSentEventsHttpResult<T>`, and JSON Lines (`application/jsonl` and the like) is
`JsonLinesHttpResult<T>`. The streams are typed by the item schema: OpenAPI 3.2 `itemSchema`, or
`x-itemSchema`, and for events the `contentSchema` of their `data`. Create them with
`StreamingResults.ServerSentEvents(events)` from an `IAsyncEnumerable<ServerSentEvent<T>>`, and
with `StreamingResults.JsonLines(items)` from an `IAsyncEnumerable<T>`. Both write and flush each
item as it comes. Pass `statusCode` when the response the document declares the stream for isn't
200, and `contentType` for another JSON Lines media type.

The endpoints bind parameters from the path, the query, headers and cookies, in the styles of the
document, e.g. exploded or delimited arrays. They read JSON, text, binary, form and multipart
bodies, and resolve the implementation from the services of the request. Since 0.12.0, they also
read:

- objects in the query, as `deepObject`, exploded form, or comma-separated keys and values;
- parameters described by JSON or text `content`;
- form fields with the `deepObject` encoding;
- file arrays whose items have `format: binary` or a `contentMediaType`.

```csharp
var app = builder.Build();
app.MapPetStoreApi();
```

Models are records with `required` properties, System.Text.Json attributes and DataAnnotations
attributes for the constraints of the schemas (`minimum`, `maxLength`, `pattern`, `format: email`,
`maxItems`, ...). An endpoint filter checks them, and the values of enums, before the
implementation is called, and answers invalid requests with 400 validation problem details.

- `oneOf` and `anyOf` with a discriminator become abstract records with `[JsonPolymorphic]`
  attributes, and their variants derive from them. On .NET 8, System.Text.Json reads the
  discriminator only as the first property of an object.
- `allOf` referencing a schema with a discriminator becomes inheritance; other `allOf` schemas are
  merged into one record.
- String enums become C# enums whose converters read and write the values of the document, e.g.
  `in-progress`. Integer enums keep their values. The `x-enum-varnames` extension names members.
- Inline object and enum schemas get types named after their location, e.g. `PetOwner` for the
  `owner` property of `Pet`. Identical inline schemas share a type.
- Schemas whose names would clash with types of .NET (`Task`, `File`, `Environment`, ...) get a
  `Model` suffix.
- Since 0.12.0, tuples (`prefixItems`), `patternProperties`, `multipleOf`, and
  `if`/`then`/`else`, `dependentRequired` and `dependentSchemas` conditions are written as for
  [`apigenie-generator client csharp`](/docs/reference/generator/client-csharp). They become lists,
  dictionaries or records with `Entries`, `[MultipleOf]` attributes, and `IValidatableObject`
  implementations, which the endpoint filter checks.

Operations with security requirements call `RequireAuthorization()`; configure the authentication
schemes in `Program.cs`, which lists the schemes of the document. Since 0.12.0, when each
alternative of the requirements lists OAuth 2.0 or OpenID Connect scopes, the endpoint answers
403 unless the user has every scope of one alternative. The scopes are read from the `scope`, `scp`
or Microsoft Entra ID scope claims (`ScopeAuthorization`).

Since 0.12.0, operations or paths with servers of their own are mapped below the path of their
first server, with the defaults of its variables, instead of below the first server of the
document. For example, `GET /health` of a server `https://status.example.com` is mapped at
`/health`. `MapPetStoreApi()` maps them outside the group it returns, so conventions added to
that group, e.g. `RequireCors()`, don't apply to them. With `base_path: none` they have no prefix
either.

Since 0.12.0, webhooks and callbacks get senders in `Senders/`. They are typed HTTP clients:

- `WebhookSender` has a method per webhook.
- Each callback of an operation has a class, e.g. `CreateShipmentStatusChangedCallback`, with a
  method per request.

Register them with `builder.Services.AddHttpClient<WebhookSender>()` and one call per callback
class; a new `Program.cs` has these calls. The methods take the URL, which the caller resolves:
the subscriber's, or the value the callback's expression names, e.g. `callbackUrl` of the request
body. Then they take the parameters and the body. They send JSON bodies with the JSON options of
the application, and return the `HttpResponseMessage`.

Not supported:

- `oneOf` and `anyOf` without a discriminator whose members have different types (typed `object`;
  members of one type, e.g. strings of different formats, give that type), and `not` other than on
  the presence and constant values of properties;
- separate request and response variants of models with `readOnly` and `writeOnly` properties
  (such properties are optional);
- conditions on anything other than the presence and constant values of properties, and
  `unevaluatedProperties`;
- in parameters, arrays of objects, objects in the label or matrix style, maps in the exploded
  form style, and `content` other than JSON or text (left out with a warning);
- the constraints of form fields, and response headers;
- request bodies of more than one kind, e.g. CSV or JSON Lines: the preferred one is accepted;
- the host of an operation's own server: its routes answer on every host;
- scopes, when an alternative of the requirements lists no OAuth 2.0 or OpenID Connect scopes
  (e.g. an API key), and the roles that OpenAPI 3.1 lists for other schemes: the endpoint only
  calls `RequireAuthorization()`;
- in the senders of webhooks and callbacks, path, object and `content` parameters, the `Accept`,
  `Content-Type` and `Authorization` header parameters, and form bodies (left out with a warning).

## Extensions

| Extension | Effect |
| --------- | ------ |
| `x-apigenie.codegen.controller-name` | on an operation or its path item: the group (API interface) of the operation, whatever `grouping` says |
| `x-apigenie.codegen.action-name` | name of the method of an operation, when `action_naming` lists `extension` |
| `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out, unless `skip_disabled` is `false` |
| `x-internal` | `true` on an operation leaves it out |
| `x-enum-varnames`, `x-enum-names` | names of the members of an enum, in PascalCase |
| `x-enum-descriptions`, `x-enumDescriptions` | documentation comments of the members of an enum |
| `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped |
| `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents: the type of the items of a streamed response |

The extensions can live in an overlay for this target instead of in the document, e.g.
`aspnet.overlay.yaml`:

```yaml
overlay: 1.0.0
info:
  title: ASP.NET names
  version: 1.0.0
actions:
  - target: $.components.schemas.PetStatus
    update:
      x-enum-varnames: [Available, OnHold, Sold]
  - target: $.paths['/pets']
    update:
      x-apigenie:
        codegen:
          controller-name: Animals
```

```sh
apigenie-generator server aspnet openapi.yaml --overlay aspnet.overlay.yaml -o out
```

## Options

### -c, --config

Path to the configuration file to use. See the "Configuration" section for more information.

### --overlay OVERLAY

Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the
extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those
listed under `commands.generate.server_aspnet.overlay` in the configuration file (with paths
relative to it). Warnings and errors about a value an overlay set point to the overlay.

### --strict

Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated)
instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`).

### --check

Writes nothing: compares what the generator would write with the output directory, prints the
files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See
[Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date).

### -o, --output

Directory where the project is generated.

### --package-name

Root namespace of the generated code, e.g. `Acme.PetStore`; also the name of the project.
Defaults to the title of the API.

### --package-version

Version of the project. Defaults to the version of the API when it's a valid .NET version, or
`1.0.0`.

### -p, --property NAME=VALUE

Sets an option (see below), e.g. `-p layout=sources`; can be repeated. Options given on the
command line take precedence over the configuration file. OpenAPI documents only: using it with an
AsyncAPI document is an error.

## Configuration

The options are read from `commands.generate.server_aspnet`. Its `asyncapi` section configures
the generation from AsyncAPI documents (see
[`apigenie-generator server aspnet` (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi#configuration)).

```yaml
version: '1.0'
commands:
  generate:
    server_aspnet:
      namespace: Acme.PetStore
      target_framework: net10.0
      grouping: url
```

| Option | Values | Description |
| ------ | ------ | ----------- |
| `layout` | `project`, `sources` | `project` (default): a complete project (.csproj, Program.cs, README.md); `sources`: only the generated sources, for an existing project |
| `namespace` | namespace | Root namespace of the generated code (also `--package-name`); derived from the API title by default |
| `target_framework` | `net8.0`, `net9.0`, `net10.0` | Target framework of the project (default: `net8.0`) |
| `grouping` | `tag`, `url` | Grouping of operations into API interfaces: by their first tag (default), or by the first segment of their paths |
| `action_naming` | `id`, `extension`, `url` | Sources of method names, in order of preference (default: `id`, `url`) |
| `validation` | `filter`, `none` | `filter` (default): an endpoint filter validates parameters and bodies against their DataAnnotations; `none`: attributes only |
| `authorization` | `require`, `none` | `require` (default): operations with security requirements call `RequireAuthorization()`; `none`: no authorization metadata |
| `base_path` | `servers`, `none` | `servers` (default): routes are prefixed with the path of the first server URL, or of the first own server of the operation or its path; `none`: no prefix |
| `program` | `true`, `false` | Generate Program.cs and stub implementations of the API interfaces (written only when missing; default: `true`) |
| `skip_deprecated` | `true`, `false` | Don't generate deprecated operations (default: `false`) |
| `skip_disabled` | `true`, `false` | Don't generate operations disabled with the `x-apigenie` extension (default: `true`) |
| `model_suffix` | text | Suffix of model names, e.g. `Dto` |
| `version` | version | Version of the project (also `--package-version`); defaults to the version of the API |

Unknown options are errors.

## Verification

The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi).

This target's support tier is [Tier 1](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first.

| Results | Level 1 | Level 2 | Level 3 |
| --- | --- | --- | --- |
| Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 70 of 77 operations pass, 2 known failures (dotnet) |
| Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | runs before a release | runs before a release, 2 known failures |
