davoc bradley
davoc bradley

Reputation: 220

Web Api routing issue when using uri parameter and query string

I'm struggling to get some Web Api 2.2 routing working correctly. I have a route:

config.Routes.MapHttpRoute(
            name: "OrgAdminGetOrgUsers",
            routeTemplate: "organisations/{id}/users",
            defaults: new { controller = "OrganisationDetails", action = "GetUsersInAnOrganisation" }                
        );

The problem I'm having is that when I add a query string for making the GET searchable, my routing stops working and I get 404's. I've looked everywhere for examples of using both Uri parameters and a query string, but I can't find anything. It seems like something people would do a lot though? When I remove the query string and the optional parameters from the controller the routing works fine.

Uri:

organisations/3/users?orderby=asc&orderByColumn=surname&start=1&end=15 

Controller:

[HttpGet]
    public IEnumerable<User> GetUsersInAnOrganisation(int id, string email = "", string firstName = "", string surname = "", string orderByColumn = "", string orderBy = "asc", int start = -1, int end = -1)

Many thanks in advance for any help!

Upvotes: 1

Views: 1774

Answers (2)

davoc bradley
davoc bradley

Reputation: 220

So I've managed to get it working, the controller needed to be declared with [FromUri] for the id parameter:

[HttpGet]
public IEnumerable<User> GetUsersInAnOrganisation([FromUri] int id, string email = "", string firstName = "", string surname = "", string orderByColumn = "", string orderBy = "asc", int start = -1, int end = -1)

Upvotes: 1

Amit Kumar Ghosh
Amit Kumar Ghosh

Reputation: 3726

This worked for me -

the config -

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
            "Default", 
            "api/{controller}/{action}/{id}", 
            defaults: new { id = RouteParameter.Optional });

the url with query params -

http://localhost:57597/api/OrganisationDetails/GetUsersInAnOrganisation/3?
orderby=asc&orderByColumn=surname&start=1&end=15

enter image description here

Hope this is helpful.

Upvotes: 0

Related Questions