I have Widget entities that belong to Company entities. There is a one-to-many relationship between Companies and Widgets.
Here's my first pass at the Get method:
[Route("MyApi/Companies/{companyId}/WidgetAdministration/[controller]")]
[HttpGet("{widgetId}")]
public async Task<ActionResult<WidgetDTO>> GetWidget([FromRoute] int companyId, [FromRoute]int widgetId)
{
WidgetDTO widgetDto = await _myContext.Widgets
.Where(w => w.CompanyId == companyId && w.WidgetId == widgetId)
.AsNoTracking()
.ProjectTo<WidgetDTO>(_mapper.ConfigurationProvider)
.FirstOrDefaultAsync();
if (widgetDto == null)
{
return NotFound();
}
else
{
return Ok(widgetDto);
}
}
if a user associated to "Company 1" requests "Company 1 Widget 55", but "Widget 55" belongs to "Company 2", what should I return?
404/NotFound - Since "Widget 55" belongs to "Company 2", the above LINQ statement will not find anything, even though "Widget 55" really does exist.
401/NotAuthorized - Since "Widget 55" does not belong to "Company 1", "Company 1" is not authorized to see it.
400/BadRequest - This is just a bad request, because the Widget and Company do not match.
As an aside, can anyone recommend a good resource to help me with other similar scenarios?