dotnet / dotnet/aspnetcore

Additional overload for `Created`

Open
#68,206 1 comment 0 reactions 0 assignees View on GitHub
api-proposal api-suggestion area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

## Background and Motivation

Currently, to send a `201 Created` response you have the following options:

- Send `201 Created` with no body or location header
- Send `201 Created` with a body *and* a location header
- Send `201 Created` with `StatusCode(StatusCodes.Status201Created, object);`

There is no corresponding Created(object?) overload for the third case.

A 201 Created response does not necessarily need to include a Location header. This can occur when an API creates a resource and needs to return information about that resource, such as its identifier, but does not expose an endpoint from which that resource can subsequently be retrieved.

Today this requires using the generic StatusCode API:

`return StatusCode(StatusCodes.Status201Created, new { id = entity.Id });`

This is less expressive than the existing Created helpers and makes a valid 201 Created response unnecessarily different from the other supported creation patterns.

## Proposed API

```diff
namespace Microsoft.AspNetCore.Mvc;

public abstract class ControllerBase
{
+ [NonAction]
+ public virtual CreatedResult Created([ActionResultObjectValue] object? value);
}

```

## Usage Examples

```csharp
await db.SaveChangesAsync(ct);

return Created(new MyReturnedObject(data));
```

## Alternative Designs

This is fairly DotNet specific as most other frameworks would have something similar to the `StatusCode` response alternate as their primary way of sending data.

## Risks

- OpenAPI behavior needs to be validated
- This proposal can spiral if it causes API inconsistency between minimal/mvc API's
- Although not ideal, `return Created("", response);` is an option as well, and may be "close enough" for most people

Contributor guide

Open the contributing guide

Research direction

Start at ControllerBase's existing Created helpers and CreatedResult, comparing them with the StatusCode path described in the issue. Check the proposed overload's OpenAPI behavior and API consistency with the existing MVC and minimal API patterns; done means the public API supports a body-only 201 response and those behaviors are validated.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
api, backend-api-design
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.