skip to content

In an ASP.NET Core controller, how do CreatedAtAction and CreatedAtRoute build the Location header, and why can they throw "No route matches the supplied values"?

level: middleimportance: must knowfreq 52%

answer

  1. 201 plus an absolute Location
  2. action name vs route name
  3. routeValues must fill the template
  4. SuppressAsyncSuffixInActionNames = true
  5. thrown while formatting the result

basics

~20 s

Both return 201 Created and generate an absolute Location URL through IUrlHelper: CreatedAtAction from an action name and route values, CreatedAtRoute from a route name. If no endpoint fits those values, they throw InvalidOperationException "No route matches the supplied values."

solid answer

~40 s

`CreatedAtAction(nameof(GetBooking), new { id = booking.Id }, booking)` returns a `CreatedAtActionResult`: status 201, the booking as the body, and a `Location` header built with `Url.Action` using the request's scheme and host, so it is absolute, such as `https://rentals.example.com/api/bookings/42`. `CreatedAtRoute("GetBooking", new { id }, booking)` does the same through a route name set with `Name = "GetBooking"` on the GET action, via `Url.Link`. The URL is generated when the result executes; if it comes back empty, the result throws `InvalidOperationException` with "No route matches the supplied values." The classic cause is `nameof(GetBookingAsync)`: MVC's `SuppressAsyncSuffixInActionNames` defaults to `true`, so the action is named `GetBooking`. Missing route values, such as passing `bookingId` when the template says `{id}`, cause it too.

code

http · 11 lines
http
POST /api/bookings HTTP/1.1
Host: rentals.example.com
Content-Type: application/json

{"bikeId": 7, "from": "2026-10-10T09:00:00Z", "hours": 3}

HTTP/1.1 201 Created
Location: https://rentals.example.com/api/bookings/42
Content-Type: application/json; charset=utf-8

{"id": 42, "bikeId": 7, "from": "2026-10-10T09:00:00Z", "hours": 3}

go deeper

for a junior

Recall that create endpoints return 201 with a Location header, and that CreatedAtAction points it at the GET action for the new resource.

for a middle

Explain how the URL is generated from action or route name plus route values, and why the Async suffix or a mismatched value name makes it throw.

for a senior

Note that the exception fires after the resource was saved, causing retries and duplicates, and guard against it with route names and integration tests on Location.

for a principal

Standardise how create endpoints identify their GET counterpart, such as route names or endpoint names, so Location headers stay correct across controllers and Minimal APIs.

## What the two helpers return A REST endpoint that creates a resource should answer **201 Created** with a `Location` header pointing at the new resource. ASP.NET Core MVC's `ControllerBase` has two helpers for it: | Helper | Identifies the target by | Builds the URL with | |---|---|---| | `CreatedAtAction(actionName, routeValues, value)` | action name (plus optional controller name) | `IUrlHelper.Action(..., request.Scheme, request.Host)` | | `CreatedAtRoute(routeName, routeValues, value)` | route name from `Name = "..."` | `IUrlHelper.Link(routeName, routeValues)` | Both produce an **absolute** URL, because the helper passes the current request's scheme and host. Both write the `value` as the response body with status 201. ## A bike-rental example ```csharp [ApiController] [Route("api/bookings")] public class BookingsController(BookingStore store) : ControllerBase { [HttpGet("{id:int}", Name = "GetBooking")] public async Task<ActionResult<Booking>> GetBookingAsync(int id) => await store.FindAsync(id) is { } b ? b : NotFound(); [HttpPost] public async Task<IActionResult> CreateAsync(NewBooking input) { var booking = await store.AddAsync(input); return CreatedAtAction("GetBooking", new { id = booking.Id }, booking); // or: return CreatedAtRoute("GetBooking", new { id = booking.Id }, booking); } } ``` A `POST /api/bookings` returns `201 Created` with `Location: https://rentals.example.com/api/bookings/42`. ## Why "No route matches the supplied values" appears The URL is generated in `OnFormatting`, when the result executes. If `IUrlHelper` returns null or empty, the result throws `InvalidOperationException("No route matches the supplied values.")`. The usual causes: 1. **The Async suffix.** `MvcOptions.SuppressAsyncSuffixInActionNames` is `true` by default, so `GetBookingAsync` is registered as the action `GetBooking`. `CreatedAtAction(nameof(GetBookingAsync), ...)` asks for an action named `GetBookingAsync`, which does not exist. Fix it with the literal `"GetBooking"`, an `[ActionName("GetBookingAsync")]` attribute, which bypasses the trimming, or `CreatedAtRoute` with a route name. 2. **Route values that do not fill the template.** The GET template is `{id:int}`; passing `new { bookingId = 42 }` leaves `id` empty, and a value that fails the `int` constraint fails too. 3. **The wrong controller.** `CreatedAtAction` assumes the current controller unless you pass `controllerName`; pointing at an action in another controller needs that argument. 4. **A route name that does not exist** or is spelled differently for `CreatedAtRoute`. ## Why the timing hurts By the time the exception is thrown, `store.AddAsync` has already saved the booking. The client receives a 500, retries, and creates a second booking. A unit test that only asserts the returned `CreatedAtActionResult` does **not** catch the problem, because URL generation has not run yet; an integration test through the test host that checks the `Location` header does. ## Choosing between the two - **`CreatedAtAction`** reads naturally when the GET action is in the same controller: pass the action name and the id. It depends on action names, so renaming or adding an `Async` suffix can break it. - **`CreatedAtRoute`** depends on a route name you chose deliberately, such as `Name = "GetBooking"`, which survives method renames and is unambiguous when several routes reach the same action. - Both need **every required route value** of the target template; values that match no template parameter end up in the query string of the `Location` URL rather than causing an error. Whichever you choose, assert the header in an integration test: post a booking, read `Location`, and issue a GET to it. ## Minimal APIs Minimal API handlers have no `ControllerBase`. They return a typed result such as `TypedResults.Created(uri, booking)`, with the URI built by injecting `LinkGenerator` and calling `GetPathByName` on an endpoint named with `WithName("GetBooking")`, or use the route-name variant of the created result. Controller route names and Minimal API endpoint names share one namespace, because `WithName` adds both endpoint-name and route-name metadata. ## What interviewers listen for - 201 plus an absolute `Location`, built from the current scheme and host. - The difference between targeting an action and targeting a route name. - The Async-suffix trap and the failing-at-execution timing. - Integration tests that assert the `Location` header.

  • Why does CreatedAtAction(nameof(GetBookingAsync), ...) fail while CreatedAtAction("GetBooking", ...) works?
    MVC trims the `Async` suffix from action names because `MvcOptions.SuppressAsyncSuffixInActionNames` defaults to `true`. The action is registered as `GetBooking`, so asking for `GetBookingAsync` finds nothing and the result throws "No route matches the supplied values." Use the trimmed name, add `[ActionName("GetBookingAsync")]`, set the option to `false`, or switch to `CreatedAtRoute` with a route name.
  • Why doesn't a unit test that calls the action directly catch a broken Location header?
    The action only returns a `CreatedAtActionResult` holding the action name and route values. The URL is generated later, in `OnFormatting`, when MVC executes the result with a real `IUrlHelper`. Only a test that runs the request through the pipeline, for example with the test host, executes that step and can assert the `Location` header.

  • Returns Ok(booking) from a create endpoint instead of 201 with a Location header.
  • Passes nameof(GetBookingAsync) to CreatedAtAction without accounting for Async-suffix trimming.
  • Believes CreatedAtAction writes a relative path in the Location header.
  • Expects a unit test on the returned result to prove the Location URL works.
  • Passes new { bookingId } when the target template parameter is {id}.