1

In my ApiController I need to handle this requests:

GET: api/User?role=theRole
GET: api/User?division=?theDivision
...
GET: api/User?other=stringValue

All these requests could be handled via a method like:

public HttpResponseMessage Get(String stringParam)

but obviously I cannot use overloading...

How can I solve this situation? Should I use a single method with optional parameters?

davioooh
  • 23,742
  • 39
  • 159
  • 250
  • you may consider encoding all your parameters into one: `GET: api/User?stringParam=role%20theRole .....` – Khanh TO Jul 06 '15 at 13:11

2 Answers2

2

According to this answer: https://stackoverflow.com/a/12620238/632604 you can write your methods like this:

public class UsersController : ApiController
    {

        // GET api/values/5
        public string GetUsersByRole(string role)
        {
            return "Role: " + role;
        }

        public string GetUsersByDivision(string division)
        {
            return "Division: " + division;
        }
    }

And Web API will route the requests just like you required:

enter image description here

Community
  • 1
  • 1
Gorgi Rankovski
  • 2,303
  • 1
  • 23
  • 32
  • Yes, you only need to prefix the name of the method with 'Get'. The routing mechanism will use query string parameters to map to the actual method. – Gorgi Rankovski Jul 06 '15 at 13:34
0

One thing that you could consider doing would be modifying the default routes in your WebApiConfig file, you'll see how the default route is set as

routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );

Change this to

routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );

You could then tag each web API action with the correct HTTP action such as [HttpGet]. To learn more about routing and handling multiple HTTP actions in Web API take a look at http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

Lonny B
  • 133
  • 1
  • 7