Skip to content

Minimal APIs endpoints require explicitly converting Async<'T> to Task<'T> #1

@brianrourkeboll

Description

@brianrourkeboll

Code like the following currently requires an explicit call to Async.StartAsTask in order for the asynchronous operation to be awaited by the framework, and for the correct response type metadata to be inferred:

get "/api/clowns/{id}" [
Status200OK, typeof<Dtos.Get.Clown>
Status404NotFound, null
Status500InternalServerError, typeof<ProblemDetails>
] (fun (logger : ILogger<Program>) (db : IDataAccess) id ->
db.Get id
|> AsyncResult.teeError (function
| Get.One.NotFound -> ()
| Get.One.DbExn e -> logger.LogError ("A database exception occurred when trying to get the clown.", e)
| Get.One.DbTimeout e -> logger.LogWarning ("A database timeout occurred when trying to get the clown.", e))
|> AsyncResult.foldResult
(Get.Clown.toDto >> Results.Ok)
(function
| Get.One.NotFound -> Results.NotFound ()
| Get.One.DbExn _ -> Results.Problem "A database exception occurred."
| Get.One.DbTimeout _ -> Results.Problem "A database timeout occurred.")
|> Async.StartAsTask)

In contrast, the equivalent code in a controller action method does not require the explicit conversion:

[<HttpGet("{id}")>]
[<ProducesResponseType(typeof<Dtos.Get.Clown>, Status200OK)>]
[<ProducesResponseType(Status404NotFound)>]
[<ProducesResponseType(typeof<ProblemDetails>, Status500InternalServerError)>]
member _.GetClown id =
dataAccess.Get id
|> AsyncResult.teeError (function
| Get.One.NotFound -> ()
| Get.One.DbExn e -> logger.LogError ("A database exception occurred when trying to get the clown.", e)
| Get.One.DbTimeout e -> logger.LogWarning ("A database timeout occurred when trying to get the clown.", e))
|> AsyncResult.foldResult
(Get.Clown.toDto >> Results.Ok)
(function
| Get.One.NotFound -> Results.NotFound ()
| Get.One.DbExn _ -> Results.Problem "A database exception occurred."
| Get.One.DbTimeout _ -> Results.Problem "A database timeout occurred.")

dotnet/aspnetcore#46898 will address this, if it is merged.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions