无法隐式转换类型'Microsoft.AspNetCore.Mvc.BadRequestObjectResult'

Rob*_*lls 4 c# asp.net .net-core

我有一个asp.net core 2.1项目,并且在控制器操作中遇到以下错误:

无法将类型“ Microsoft.AspNetCore.Mvc.BadRequestObjectResult”隐式转换为“ System.Collections.Generic.IList”。存在显式转换(您是否缺少演员表?)

这是我的代码:

[HttpPost("create")]
[ProducesResponseType(201, Type = typeof(Todo))]
[ProducesResponseType(400)]
public async Task<IList<Todo>> Create([FromBody]TodoCreateViewModel model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);   // This is the line that causes the intellisense error
    }

    await _todoRepository.AddTodo(model);
    return await GetActiveTodosForUser();
}


[HttpGet("GetActiveTodosForUser")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public async Task<IList<Todo>> GetActiveTodosForUser(string UserId = "")
{
    if (string.IsNullOrEmpty(UserId))
    {
        UserId = HttpContext.User.FindFirstValue(ClaimTypes.Sid);
    }
    return await _todoRepository.GetAll(UserId, false);
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

ama*_*kkg 17

您的操作返回类型没有考虑到可能BadRequest

IList<Todo>您需要用泛型ActionResult类型将其包装起来,而不是直接使用。

public async Task<ActionResult<IList<Todo>>> Create(...

这是相关的文档


spo*_*ahn 11

对于ASP.NET 2.1的核心,你应该使用ActionResult<T>,但有一个限制使用Interface的。

这个作品

public ActionResult<IList<string>> Create()
{  
    return new List<string> { "value1", "value2" };
}
Run Code Online (Sandbox Code Playgroud)

不工作

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;
}
Run Code Online (Sandbox Code Playgroud)

C# 不支持接口上的隐式转换运算符。因此,需要将接口转换为具体类型才能使用 ActionResult。

来源:ActionResult 类型



旁注:您不需要,[FromBody]因为 ASP.NET 会自动执行此操作。 更多在这里


Wiq*_*iqi 5

实际上,对于以下ASP.NET Core 2.1,您需要返回IActionResult而不是IList

public async Task<IActionResult> Create([FromBody]TodoCreateViewModel model)
Run Code Online (Sandbox Code Playgroud)

然后它将起作用。

对于@amankkg建议的ASP.NET Core 2.1,

public async Task<ActionResult<IList<Todo>>> Create([FromBody]TodoCreateViewModel model)
Run Code Online (Sandbox Code Playgroud)