welp_
welp_

Reputation: 1

Getting an item by ID

I am working on a todo list project. I can post todo items and get todo items but I cannot get a single todo item by ID. Would this error be in my controller?


    [HttpGet("{id}", Name = "GetTodoItem")]
    public async Task<ActionResult<Todo>> GetTodoItem(int? id)
    {
        if (id != null)
            return new NotFoundResult();
        
        var todo = await _context.Todos.FindAsync(id);

        return Ok(todo);
    }

    

I have been looking for all over for a solution, any feedback will help.

Upvotes: 0

Views: 178

Answers (1)

Charles Han
Charles Han

Reputation: 2010

Your problem is at this line,

if (id != null)
    return new NotFoundResult();

Should be,

if (id == null)
    return new NotFoundResult();

But what you really should do is,

    if (id == null) //I don't think this will happen as the model binding will generate an error automatically. You can test it out yourself.
        return new BadRequestResult();
    
    var todo = await _context.Todos.FindAsync(id);

    if (todo == null)
       return new NotFoundResult();

    return Ok(todo);

Upvotes: 1

Related Questions