In ASP.NET 6, the standard way to return a 404 from a Controller action is with
return NotFound();
And if you want to return a message with it, you can do
return NotFound($"Couldn't find an account with id {accountId}.");
Which returns:
Couldn't find an account with id 123.
Which isn’t ideal. Ideally we want to return a ProblemDetails like a nice API should. I found this workaround:
return Problem(statusCode: StatusCodes.Status404NotFound, detail: $"Couldn't find an account with id {accountId}");
Which returns us a ProblemDetails:
{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.4", "title": "Not Found", "status": 404, "detail": "Couldn't find an account with id 123.", "traceId": "00-8292718bbb9d727dd1108abe3165deac-82f256594498617d-00" }
Similarly, for 400s, you might think the best thing to return is
return BadRequest("Invalid accountId.");
But sadly my friend, as with NotFound(“…”) above, you’ll just get a 400 with a string in the request body. To return a ProblemDetails with a 400, you can call
ModelState.AddModelError(nameof(accountId), "must be greater than zero"); return ValidationProblem(ModelState);
Which gives you:
{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "One or more validation errors occurred.", "status": 400, "traceId": "00-3ae564a748991dee1d1a269d73e73b3f-bcdb5d6686a1b66a-00", "errors": { "accountId": [ "must be greater than zero" ] } }
Or if you’re not happy with the shape of that response, you could use Problem() as above:
return Problem(statusCode: StatusCodes.Status400BadRequest, detail: $"{nameof(accountId)} must be greater than zero.");
{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "Bad Request", "status": 400, "detail": "accountId must be greater than zero.", "traceId": "00-0fc60678b8c5dee4e6d22faa40d8f12a-4e1992ddf4c43cd0-00" }
While we’re on the topic, don’t forget to decorate your controller actions with these responses:
[SwaggerResponse(StatusCodes.Status400BadRequest, null, typeof(ProblemDetails), "application/problem+json")] [SwaggerResponse(StatusCodes.Status404NotFound, null, typeof(ProblemDetails), "application/problem+json")]