Home > Net >  What is the best approach to pass an id and model together in PUT method?
What is the best approach to pass an id and model together in PUT method?

Time:01-20

I am writing an asp.net webAPI app, and I'm wondering: what is the best approach to pass an id and an updatedModel? Let's consider, that now I have such method:

[Authorize(Policy = "WriteAccess")]
[HttpPut("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<ActionResult> PutCategory(Guid id, CategoryDTO categoryDTO)
{
}

In case if you have an Id property in your DTO class, you will pass id twice (as a param Guid id to find an entity to be updated, and as a part of DTO entity). And in case of mistakes in front-end calling my API I have to catch such cases when the id and DTO.Id are deifferent. What is the "right" or recomended approach to write the PUT methods accepting an id and DTO with Id prop? If there is no recomended approach for such cases, should I avoid using an Id in DTO, or should I create an additional DTO just for PUT method? In case of questions, my DTO is as simple as that:

public class CategoryDTO
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string CategoryDescription { get; set; }
}

CodePudding user response:

The first solution that comes to mind is to conditionally set them if they're not already set.

public async Task<ActionResult> PutCategory(Guid id, CategoryDTO categoryDTO)
{
  categoryDTO.id ??= id; // set if categoryDTO.id not set
  id = categoryDTO.id; // sync both values
}

CodePudding user response:

I would send the Id in DTO and not send it as a separate field. So the method will be as below:

[Authorize(Policy = "WriteAccess")]
[HttpPut("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<ActionResult> PutCategory(CategoryDTO categoryDTO)
{
}
  • Related