Skip to content

Update ProducesResponseTypeAttribute to support setting content types for the defined response #34542

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

Closed
Tracked by #34514
DamianEdwards opened this issue Jul 20, 2021 · 1 comment · Fixed by #34906
Closed
Tracked by #34514
Assignees
Labels
area-minimal Includes minimal APIs, endpoint filters, parameter binding, request delegate generator etc enhancement This issue represents an ask for new feature or an enhancement to an existing one feature-minimal-actions Controller-like actions for endpoint routing old-area-web-frameworks-do-not-use *DEPRECATED* This label is deprecated in favor of the area-mvc and area-minimal labels Priority:1 Work that is critical for the release, but we could probably ship without
Milestone

Comments

@DamianEdwards
Copy link
Member

DamianEdwards commented Jul 20, 2021

The Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute implements IApiResponseMetadataProvider today but does not support setting the content types associated with the response type defined by the attribute instance. This limitation means there is no way to specify the content type produced for specific status codes for a given endpoint, despite the OpenAPI specification supporting this.

Customers have indicated they have a need for this support in the OpenAPI library for ASP.NET Core, Swashbuckle too, see domaindrivendev/Swashbuckle.AspNetCore#1691

Take the following common example. A single endpoint can return either 400 Bad Request with a validation problem formatted as application/problem+json, or a 201 Created with the created resource formatted as application/json:

app.MapPost("/todos", async (Todo todo, TodoDb db) =>
    {
        if (!MinimalValidation.TryValidate(todo, out var errors))
            return Results.ValidationProblem(errors);

        db.Todos.Add(todo);
        await db.SaveChangesAsync();

        return Results.CreatedAtRoute("GetTodoById", new { todo.Id }, todo);
    })
    .WithName("AddTodo")
    .Produces<HttpValidationProblemDetails>(StatusCode.Status400BadRequest, "application/problem+json")
    .Produces<Todo>(StatusCodes.Status201Created, "application/json");

This would be represented in an OpenAPI document like this:

"/todos": {
    "post": {
        "tags": [
            "TodoApi"
        ],
        "requestBody": {
            "content": {
                "application/json": {
                    "schema": {
                        "$ref": "#/components/schemas/Todo"
                    }
                }
            }
        },
        "responses": {
            "201": {
                "description": "Success",
                "content": {
                    "application/json": {
                        "schema": {
                            "$ref": "#/components/schemas/Todo"
                        }
                    }
                }
            },
            "400": {
                "description": "Bad Request",
                "content": {
                    "application/problem+json": {
                        "schema": {
                            "$ref": "#/components/schemas/HttpValidationProblemDetails"
                        }
                    }
                }
            }
        }
    }
}

We should update Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute to support defining the content types associated with the declared response type, e.g.:

public class ProducesMetadataAttribute : ProducesResponseTypeAttribute, IApiResponseMetadataProvider
{
    public ProducesMetadataAttribute(int statusCode) : base(statusCode) { }
    public ProducesMetadataAttribute(Type type, int statusCode) : base(type, statusCode) { }
+   public ProducesMetadataAttribute(Type? type, int statusCode, string? contentType, params string[] additionalContentTypes) : base(statusCode) { }

+   public MediaTypeCollection ContentTypes { get; set; } = new();

-   void IApiResponseMetadataProvider.SetContentTypes(MediaTypeCollection contentTypes) { } 
+   public void SetContentTypes(MediaTypeCollection contentTypes) { }
}

This change would work in conjunction with #33924 to enable endpoints to describe the content types they return for each status code and response type. Endpoints that don't specify a content type should default to being described as returning application/json inline with the default minimal APIs behavior.

@DamianEdwards DamianEdwards added area-runtime feature-minimal-actions Controller-like actions for endpoint routing labels Jul 20, 2021
@DamianEdwards DamianEdwards changed the title ProducesResponseTypeAttribute needs to be updated to support setting content types. Endpoints that don't specify a content type should default to being described as returning "application/json" inline with the default minimal APIs behavior. Update ProducesResponseTypeAttribute to support setting content types for the defined response Jul 20, 2021
@ghost
Copy link

ghost commented Jul 20, 2021

Thanks for contacting us.

We're moving this issue to the Next sprint planning milestone for future evaluation / consideration. We would like to keep this around to collect more feedback, which can help us with prioritizing this work. We will re-evaluate this issue, during our next planning meeting(s).
If we later determine, that the issue has no community involvement, or it's very rare and low-impact issue, we will close it - so that the team can focus on more important and high impact issues.
To learn more about what to expect next and how this issue will be handled you can read more about our triage process here.

@rafikiassumani-msft rafikiassumani-msft added enhancement This issue represents an ask for new feature or an enhancement to an existing one Priority:1 Work that is critical for the release, but we could probably ship without labels Jul 20, 2021
@davidfowl davidfowl added old-area-web-frameworks-do-not-use *DEPRECATED* This label is deprecated in favor of the area-mvc and area-minimal labels and removed area-runtime labels Jul 31, 2021
captainsafia added a commit that referenced this issue Aug 6, 2021
* Support setting content types in ProducesResponseTypeAttribute to close #34542

* Add WithName extension method to resolve #34538

* Support setting endpoints on group names to resolve #34541

* Add OpenAPI extension methods to resolve #33924

* Add tests for new OpenAPI methods

* Add endpoint metadata attributes

* Update PublicAPI files with deltas

* Add support for SuppressApi to close #34068

* Update tests to account for supporting setting content types

* Fix up PublicAPI analyzer warnings

* Clean up source files

* Address feedback from API review

* Fix typo and update type signature

* Apply feedback from second API review

* Update docstrings

* Apply suggestions from code review

Co-authored-by: Martin Costello <[email protected]>

* Address non-test related feedback

* Handle setting content types for ProducesResponseType attribute

* Address feedback from peer review

* Add test for ProducesResponseType override scenario

Co-authored-by: Martin Costello <[email protected]>
@ghost ghost locked as resolved and limited conversation to collaborators Sep 7, 2021
@amcasey amcasey added the area-minimal Includes minimal APIs, endpoint filters, parameter binding, request delegate generator etc label Jun 2, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-minimal Includes minimal APIs, endpoint filters, parameter binding, request delegate generator etc enhancement This issue represents an ask for new feature or an enhancement to an existing one feature-minimal-actions Controller-like actions for endpoint routing old-area-web-frameworks-do-not-use *DEPRECATED* This label is deprecated in favor of the area-mvc and area-minimal labels Priority:1 Work that is critical for the release, but we could probably ship without
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants