Search code examples
c#asp.netasp.net-mvcasp.net-coreasp.net-web-api

CS0029 error when returning NotFound() method in controller function


How do I handle this error in a controller function?

I get CS0029 error when returning NotFound() method...

    [HttpGet("{id}")]
    public async Task<Database?> GetById(string id)
    {
        var response = await _databasesService.GetById(id);

        var database = response.FirstOrDefault();

        if (database is not null)
            return database;
        else
            return NotFound(); // Error CS0029
    }


Solution

  • Your method is expecting a return type of Database? type, so you can't cast a NotFound object to that. To fix this, change your method signature to return a Task<ActionResult<Database>>, for example:

    public async Task<ActionResult<Database>> GetById(string id)
    {
       ...
    }