Cannot implicitly convert type 'Microsoft.AspNetCore.Mvc.BadRequestObjectResult'
Actually you need to return IActionResult instead of IList for below ASP.NET Core 2.1,
public async Task<IActionResult> Create([FromBody]TodoCreateViewModel model)
Then it will work.
And for ASP.NET Core 2.1 as suggested by @amankkg,
public async Task<ActionResult<IList<Todo>>> Create([FromBody]TodoCreateViewModel model)
For ASP.NET Core 2.1, you should use ActionResult<T>
but there is a limitation with Interface
's.
This Works
public ActionResult<IList<string>> Create()
{
return new List<string> { "value1", "value2" };
}
Doesn't Work
public ActionResult<IList<string>> Create()
{
//DOESN'T COMPILE:
//Error CS0029 Cannot implicitly convert type
//'System.Collections.Generic.IList<string>'
//to 'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IList<string>>'
//the cast here is for demo purposes.
//the problem will usually arise from a dependency that returns
//an interface.
var result = new List<string> { "value1", "value2" }
as IList<string>;
return result;
}
C# doesn't support implicit cast operators on interfaces. Consequently, conversion of the interface to a concrete type is necessary to use ActionResult.
Source: ActionResult type
- Demo project
- Interesting read on C# doesn't support implicit cast operators on interfaces
Sidenote: you don't need [FromBody]
as ASP.NET will do that automatically. More here.
Your action return type does not take in mind possible BadRequest
.
Instead of direct usage of IList<Todo>
you need to wrap it with generic ActionResult
type.
public async Task<ActionResult<IList<Todo>>> Create(...
Here are the related docs.