Reputation: 6715
Consider a controller action like this:
[HttpGet]
[Route("blog/{slug}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<Blog> Get(string slug)
{
return await Task.Run(() =>
{
var model = Data.GetBlog(slug);
if (model == null)
{
return NotFound();
}
return Ok(model);
});
}
I am getting an error for each of the returns:
Cannot implicitly convert type 'Microsoft.AspNetCore.Mvc.NotFoundResult' to 'System.Threading.Tasks.Task'
Cannot implicitly convert type 'Microsoft.AspNetCore.Mvc.OkObjectResult' to 'System.Threading.Tasks.Task'
Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
If I comment out either one of the response types (so only have the NotFound()
or only have the Ok()
), it compiles fine.
I thought both inherit from same base class and so both could be used within the same action.
Where am I going wrong?
p.s. The Task.Run is me being lazy until I write the async Data
methods.
Upvotes: 2
Views: 15685
Reputation: 247108
The Task.Run
code is returning IActionResult
derived results that you try to return as a Blog
type. Hence the error
This is what the ActionResult<T>
is for.
Consider the following refactor.
[HttpGet]
[Route("blog/{slug}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<Blog>> Get(string slug) {
Blog model = await Task.Run(() => Data.GetBlog(slug));
if (model == null) {
return NotFound();
}
return model;
}
Reference Controller action return types in ASP.NET Core Web API
Upvotes: 8