dotnet / dotnet/aspnetcore

ProducesAttribute seems to ignore named parameters in OpenAPI document generation

Open
#57,995 1 comment 0 reactions 0 assignees View on GitHub
area-mvc feature-openapi
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

I am using the `Produces` attribute to describe the response types for an endpoint method in a controllers-based app. Some simple scenarios work as expected, such as

```csharp
[Produces(typeof(ResponseBody))]
```

which produces the following `responses` for the operation in the generated OpenAPI:

```json
"200": {
"description": "OK",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ResponseBody"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ResponseBody"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ResponseBody"
}
}
}
}
```

But this attribute fails to capture the type information for the response body:

```csharp
[Produces("application/json", Type = typeof(ResponseBody))]
```

Here the response in the generated OpenAPI is just:

```json
"200": {
"description": "OK",
"content": {
"application/json": {}
}
}
```

To work around this, I tried creating a custom subclass of the ProducesAttribute to set the fields:

```csharp
public class ProducesJsonAttribute : ProducesAttribute
{
public ProducesJsonAttribute() : base(typeof(ResponseBody))
{
ContentTypes = new MediaTypeCollection() { "application/json" };
}
}
```

and then using `[ProducesJson]` on the endpoint method, but this also fails to capture the type information:

```json
"200": {
"description": "OK",
"content": {
"application/json": {}
}
}
```

Finally, I was unable to use named parameters on the generic `ProducesAttribute\` because it would not compile. This code:

```csharp
[Produces(ContentTypes = new []{"application/json"})]
```

generates a build error:

```text
/workspaces/aspnet-openapi-samples/Controllers/Responses/Controllers/ResponsesController.cs(43,29): error CS0655: 'ContentTypes' is not a valid named attribute argument because it is not a valid attribute parameter type
```

### Expected Behavior

I expect all the metadata specified in the attribute to appear in the generated OpenAPI document.

### Steps To Reproduce

I have a project I can share if needed.

### Exceptions (if any)

_No response_

### .NET Version

9.0.100-rc.1.24452.12

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.