Why do we send the identity and the entity when we do a HttpPut request

41 views Asked by At

Why do we send the identity and the entity when we do a HttpPut request. The Id is already set on the model.

This is the code generated by Visual Studio 2019

  [HttpPut("{id}")]
  public async Task<IActionResult> PutReport(int id, Report report)
  {
      if (id != report.Id)
      {
          return BadRequest();
      }
      _context.Entry(report).State = EntityState.Modified;
      try
      {
          await _context.SaveChangesAsync();
      }
      catch (DbUpdateConcurrencyException)
      {
          if (!ReportExists(id))
          {
              return NotFound();
          }
          else
          {
              throw;
          }
      }
      return NoContent();
  }

This is the code I would write if I had never seen the code generated by VS.

[HttpPut]
public async Task<IActionResult> PutReport(Report report)
{
    if (report.Id == 0)
    {
        return BadRequest();
    }
    _context.Entry(report).State = EntityState.Modified;
    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!ReportExists(report.Id))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }
    return NoContent();
}

So what does the Id bring to the table??

1

There are 1 answers

0
Bryan Lewis On BEST ANSWER

This has more to do with convention than with strict need for the ID to be in the route. Visual Studio's template follow the RESTful style of creating APIs, and that style/convention states that the PUT endpoint should represent the entity being updated. A route/URL without an ID (e.g. "/report") doesn't represent a specific report being updated (even if the ID is in the payload), while the one with an ID does (e.g. "/report/12345").

If this is a public facing API, then I would strongly suggest you follow the general REST conventions and include the ID in the route. If not, then you have as much flexibility as you want, BUT at the cost of not following the general convention that most REST APIs follow (which may make someone else reading your code confused).

Some people include the ID in both the route and the model, some go just in the route and it's perfectly possible to only go only in the model also. But if you want to maintain the general RESTful quality, I would suggest keeping it int he route regardless of whether you want it in the model or not.