Search code examples
c#asp.net-coreasp.net-core-webapiasp.net-core-routing

How to build server url for DTOs


I want to add a url to my DTOs, specifically a canonical link for each object in a collection. I'm using Dapper to map my SQL result into a collection, so I was hoping to do this within the POCO itself.

public class Group {
 public string Name { get; set; }
 public string url {
  get {
    //CODE TO BUILD LINK HERE (e.g., https://example.com/v1/groups/1234)
  }
 }
}

I've seen use of Url.Link() but I've only gotten that to work within my controller - not my url property above. If it can't be done within the POCO, is there a preferred way to update my collection of Group objects after Dapper loads them?


Solution

  • After dapper/service loads the records, you will then need to traverse the collection and generate the URL based on the identifier for the record and the route

    Assuming

    public class Group {
        public string Name { get; set; }
        public string Url { get; set; }
    }
    

    A controller that generates the record URL could follow the following pattern

    [Route("v1/groups")]
    public class GroupsController : Controller {
    
        //...omitted for brevity
    
        //GET v1/groups
        [HttpGet("")]
        public IActionResult Get() {
            IEnumerable<Group> groups = service.GetGroups()
                .Select(group => {            
                    var url = Url.RouteUrl("GetGroup", new { name = group.Name });
                    group.Url = url;
                    return group;
                }).ToList();
            if(!groups.Any()) return NotFound();
            return Ok(groups);
        }
    
        //GET v1/groups/1234
        [HttpGet("{name}", Name = "GetGroup")]
        public IActionResult Get(string name) {
            var group = service.GetGroup(name);
            if(group == null) return NotFound();
            group.Url = Url.RouteUrl("GetGroup", new { name = group.Name });
            return Ok(group);
        }
    }
    

    Reference Generating URLs by route