Israel Ocbina
Israel Ocbina

Reputation: 577

Is it fine to use "return Ok(await result)" in MVC/.Net Core

I got this sample code I used in MVC/.Net Core Controller

 public async Task<IActionResult> GetData([FromQuery]string id, CancellationToken cancellationToken)
        {
            Person person= new Person { 
                Id = id,
                Name = "Test name"
            };
            return Ok(await Task.FromResult(person));
        }

The await is it fine to use inside Ok() ?

Upvotes: 1

Views: 4510

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457047

It's fine to use await when passing parameters to Ok (or any other method).

return Ok(await SomeMethodAsync());

is roughly equivalent to

var result = await SomeMethodAsync();
return Ok(result);

which is roughly equivalent to

var resultTask = SomeMethodAsync();
var result = await resultTask;
return Ok(result);

Upvotes: 6

Related Questions