简体   繁体   中英

How can Ok() be both Task<IActionResult> and IActionResult?

In a Controller in .NET Core you can return Ok() as an IActionResult . But I do not understand how it can also return a Task<IActionResult> .

Example:

    public class FooController : Controller
    {

        [HttpGet]
        public async Task<IActionResult> OkResultAsync()
        {
            // This is ok. But I don't get why since OkResult != Task<IActionResult>
            OkResult result = Ok();
            return result;
        }

        [HttpGet]
        public IActionResult OkResult()
        {
            // This is ok, and it seems logical since OkResult implements IActionResult.
            OkResult result = Ok();
            return result;
        }

        [HttpGet]
        public FooResult Bar()
        {
            // This is ok.
            return new FooResult();
        }

        [HttpGet] 
        public async Task<FooResult> BarAsync()
        {
            // This is not ok since FooResult != Task<FooResult>
            return new FooResult();
        }
    }

Ok() returns a OkResult , which in turn implements IActionResult . How does .NET know how to handle it (without awaiting) if the method signature is returning a Task<IActionResult> ?

The async keyword causes the compiler to take care of this automatically. Async methods implicitly "wrap" the return value in a Task.

async Task<int> GetNumber()
{
    return 42;
}

vs

Task<int> GetNumber()
{
    return Task.FromResult(42);
}

The async keyword is a shorthand that wraps the contents of the method in a Task. When you return inside an async method the compiler wraps it up into a Task for you. For example these two methods are essentially the same:

private static Task<string> Hello()
{
    return new Task<string>(() => "hello");
} 

private static async Task<string> AsyncHello()
{
    return "hello";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM