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)
我究竟做错了什么?
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。
旁注:您不需要,[FromBody]因为 ASP.NET 会自动执行此操作。 更多在这里。
实际上,对于以下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)
| 归档时间: |
|
| 查看次数: |
9334 次 |
| 最近记录: |