Home > Net >  What does my HttpPut request require to work as intended in ASP.NET Core?
What does my HttpPut request require to work as intended in ASP.NET Core?

Time:06-14

I'm working on a simple notes api, I'm trying to create a Put method to update a note in my notes list, but when I try to update any note through the SwaggerUI I get a the 404 status code.

This is my [HttpPut] request:

[HttpPut("{id}")]
    public IActionResult Put([FromBody] Note requestParam)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest("Not a valid model");
        }

        using (_datacontext)
        {
            var ExistingNote = _datacontext.Note.Where(n => n.Id == requestParam.Id)
                                        .FirstOrDefault<Note>();

            if (ExistingNote != null)
            {
                ExistingNote.Title = requestParam.Title;
                ExistingNote.Description = requestParam.Description;
                ExistingNote.Completed = requestParam.Completed;

                _datacontext.SaveChanges();
            } else
            {
                return NotFound();
            }
        }

        return Ok();
    }

My DataContext:

public class DataContext : DbContext
{
    public DataContext(DbContextOptions<DataContext> option) : base(option)
    {

    }

    public DbSet<Note> Note { get; set; }
    
}

And lastly my Note Model:

public class Note
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public bool Completed { get; set; }
}

I've researched about Http bodies since it seemed like it needed to be part of the request but still get the error code. What could be wrong with it? (Both post and get methods work!).

Also, the error code: Status error 404

CodePudding user response:

When using the [HttpPut("{id}")] attribute on your controller, you need to add a parameter to the controller method's signature:

IActionResult Put([FromRoute] int Id, [FromBody] Note requestParam)

You can then call the API like this when Id=123

PUT http://{base-url}/123

Then you need to query the data context using the id from the route (which means you can remove it from the body)


On the other hand, if you don't want the Id as part of the request URL and keep it in the body, you need to remove the Id from the route template: [HttpPut] without {id}.


Needless to say, make sure the Id actually exists in the data context. Otherwise your code will return, yes, a 404.

  • Related