相关文章推荐

C# – Cannot implicitly convert type ‘Microsoft.AspNetCore.Mvc.BadRequestObjectResult’

.net-core asp.net c++

I have an asp.net core 2.1 project and I'm getting the following error in my controller action:

Cannot implicitly convert type 'Microsoft.AspNetCore.Mvc.BadRequestObjectResult' to
'System.Collections.Generic.IList'. An explicit
conversion exists (are you missing a cast?)

This is my code:

[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);

What am I doing wrong?

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.

 
推荐文章