Adam Adam -3 years ago 186
C# Question

WebApi - UrlHelper.Route to GET with [FromUri] object parameter

I have an API action defined as the following:

[Route(Name="GetMembersTest"), HttpGet, ResponseType(typeof(MemberHeadersDto))]
public IHttpActionResult GetMembers[FromUri]MemberFilterDto filter, [FromUri]PagingOptionsDto paging)


This method works as expected, routing and all, requests are flowing through just fine. However, I'd like to supply a "NextUri" for paging so that the caller can just keep following NextUri until it is null to get all the results. I have to send back a uri to the same action, 1 page ahead, if that makes sense.

So I tried using UrlHelper.Route. This route is named "GetMembers" for the purpose of this example.

NextUri = Url.Route("GetMembers", new { filter, paging });


The problem is that instead of getting something like

/v1/members?filter.q=&filter.otherproperty=&paging.count=10&paging.startRow=11


I get

/v1/members?filter=WebApi.Models.MemberFilterDto&paging=WebApi.Models.PagingOptionsDto


It looks like UrlHelper.Route doesn't support complex types in the [FromUri] parameter of a GET Request. Is there anything I can do to get this functionality? My workaround right now is to take in all the Dto properties as individual parameters then build my Dtos from them on the server. This isn't ideal because if I ever add any more options I'd have to add more parameters to the action, which also makes the route value dictionary more fragile as well because it has to match with the method signature in UrlHelper.Route(routeName,routeValues).

Answer Source

Unfortunately, there is no way to pass in complex object to routing. Instead, you will need to pass in the simple properties individually.

I was not able to find a way to extend Url.Route, but that would be/have been your best option.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download