I created an ASP.NET Core Web API project with Entity Framework Core and scaffolded a new "API controller with actions, using Entity Framework" and, while it's wonderful, I get the feeling the default PUT
and POST
methods are swapped and would like some feedback on the matter:
// PUT: api/Items/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPut("{id}")]
public async Task<IActionResult> PutItem(long id, Item Item)
{
if (id != Item.Id)
{
return BadRequest();
}
_context.Entry(Item).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ItemExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Items
[HttpPost]
public async Task<ActionResult<Item>> PostItem(Item Item)
{
_context.Items.Add(Item);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetItem), new { id = Item.Id }, Item);
}
private bool ItemExists(long id)
{
return _context.Items.Any(e => e.Id == id);
}
As far as I know PUT
should provide an object to be added to the database, while PATCH
should be used to update an existing object. But from what I see in this code PUT
is being used to update an already existing item, specifying an id that must already exist, while POST
just uploads a new resource, without specifying any id, how I imagine a PUT
should work.
Am I wrong or should I swap the HttpPut
for HttpPatch
and the HttpPost
for HttpPut
?