I want to return a url as a property in my Group. I can do it from the GetGroup() method when returning a single Group but I only get null when I run the code in the GetGroups() method (returning a collection of Groups). I thought maybe I was misusing the iterator but I'm able to update the objects in the collection with hard coded values. It just seems like LinkGenerator doesn't find my uri when called from GetGroups().
I'm not sure if I have a routing problem or just not understanding how this works.
[Authorize]
[ApiController]
[ApiVersionNeutral]
[ApiConventionType(typeof(DefaultApiConventions))]
[Route("v{version:apiVersion}/{providerId}/[controller]")]
public class GroupsController : ControllerBase
{
//...omitted code...
public GroupsController(IGroupsService groupsService, LinkGenerator linkGenerator)
{
this.groupsService = groupsService;
this.linkGenerator = linkGenerator;
}
// GET: api/0000/groups/1000
// Get a group
[HttpGet("{groupId}", Name="GetGroup")]
[ApiConventionMethod(typeof(DefaultApiConventions), nameof(DefaultApiConventions.Get))]
public async Task<ActionResult<Group>> GetGroup(int providerId, int groupId)
{
Group group = await this.groupsService.GetGroup(providerId, providerId, groupId);
if (group == null)
return NotFound();
else
group.Url = linkGenerator.GetUriByAction(HttpContext, action: "GetGroup", controller: "Groups", values: new { providerId, groupId });
return Ok(group);
}
// GET: api/0000/groups
// Get all groups
[HttpGet]
[ApiConventionMethod(typeof(DefaultApiConventions), nameof(DefaultApiConventions.Get))]
public async Task<ActionResult<IEnumerable<Group>>> GetGroups(int providerId)
{
IEnumerable<Group> groups = await groupsService.GetGroups(providerId, providerId);
if (groups == null)
return NotFound();
else
{
foreach (Group g in groups)
{
g.Url = linkGenerator.GetUriByAction(HttpContext, action: "GetGroup", controller: "Groups", values: new { providerId = g.ProviderID, groupId = g.GroupID });
}
}
return Ok(groups);
}
//...omitted code...
}